MurifoX
MurifoX

Reputation: 15089

Auto executing javascript code loaded dynamically

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?

Upvotes: 0

Views: 69

Answers (2)

metadings
metadings

Reputation: 3848

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?

Upvotes: 2

synthomat
synthomat

Reputation: 774

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();
});

Upvotes: 2

Related Questions