Let's say i have main page:
<html>
// Blah blah blah
<button />
// Blah blah blah
<script type="text/javascript">
// Nothing here
</script>
</html>
That button on the main page open a modal with the following structure:
<div>
<!-- HTML Stuff -->
</div>
<script type='text/javascript'>
$(function() {
// hide stuff, show stuff
});
function whatever() {
// do some stuff
}
</script>
This modal is loaded into my DOM.
The question is:
Why the whatever function can't be called in the context of the modal?
For example, if i had a select tag inside the modal and added an eventListener to it so that when fired, it would call the whatever function, like this:
$('#select').on('change', function() {
whatever();
});
Or even:
<select onchange="whatever()" />
If i move the function to the main page, outside the modal it works like a charm.
Does it have something to do with the code being executed and losing all references when it is loaded dinamically?
2 Answers 2
Did you try something like this (semi-pseudo-code ;-)
Modal:
function initModal() {
$('#select').on('change', function() {
whatever();
});
}
Main Page:
$.get('modal.html').success(function() {
initModal();
});
1 Comment
The problem is, the dynamically loaded script is executed before the html is inserted into the DOM.
Have a look on my answer to How to append javascript block in a string into html?
2 Comments
$(document).on("change", "#select", function () { }); or a custom init that gets called in a $.get callback, but for a more general approach I made it with the style script trick/hack
whateverin global scope?