0

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?

5
  • 1
    You need to show us more...Give us an example how does it not work. Commented Feb 11, 2014 at 13:42
  • 1
    Please show how are you trying to call that function. Commented Feb 11, 2014 at 13:43
  • Why don't you call whatever() from the "load success"-hook in your loadModal-routine? Commented Feb 11, 2014 at 13:45
  • I have edited the question to give more insight. Commented Feb 11, 2014 at 13:48
  • Are you sure whatever in global scope? Commented Feb 11, 2014 at 13:50

2 Answers 2

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

That's a great solution to the problem, but what i really want is to understand why the problem happened.
2

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

Hmm, that's good to know. So you are saying that everything would be executed and no function reference will exist if i load it like that?
Yes, sadly I noticed this since jQuery 1.4+ (afair) that scripts are removed and no more living in javaScript global space. So if you want to do something simple you may get away with $(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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.