2

Let's say I have those divs with some code in the same document:

<div id="trigger">Click Me!</div>
<div id="handler">Handler</div>

<script type="text/javascript">
    $("#handler").on('check', function() {alert('Handler is working!');})
    $("#trigger").on('click', function()
       {$("#handler").trigger('check');alert('Trigger is working!')
    })
</script>

It's working as expected.

However, if I use .load() to inject all this into a page, then only the (native) trigger event, not the (custom) handler event is working.

I guess it has something to do with timing but I thought .on() was supposed to take care of timing issues?

EDIT: THE SOLUTION


I got it all wrong. I wasn't aware that a document loaded simultaneously with the above had its own reference to the Jquery source. So a different version of Jquery was loaded on top of the one already in the DOM. Now it's working without .ready() and even with the original syntax. Thanx!

  • If you load everything into the page, the script as well as the elements you bind to, then it might even be enough to wrap your code into a `$(document).ready(function(){//your code here});` which will wait with the execution until the DOM is ready. Otherwise, if you only inject the HTML but not the script then you need to use the `on()` overload for dynamic bindings alright as mentioned by `Mash`. – Nope Jan 27 '13 at 16:08
  • I tried that and found with the help of alert() that when injecting with .load() the code ran in exactly the same order as injected, no mather if I put it in $(document).ready(), $(window).ready() or outside any of those functions. – Martin Fransson Jan 27 '13 at 17:50

2 Answers2

2

What you are trying to do is access the element #handler before it exists (.load takes some time to pull it into the page).

Instead, .on also supports the ability to listen on elements that don't yet exist.

$("body").on("click", "#handler", function() { alert("Clicked on #handler"); });

This will listen on the body element (which should exist) for any click on an element with ID #handler, even if it is later injected.

mash
  • 14,851
  • 3
  • 30
  • 33
  • Thanks, I didn't know that .on() differs in functionality depending on syntax. Unfortunately my example code was too much simplified. In my real code I simultaneously load two other (unrelated) divs with $.post. I've now found that if I comment out those two calls it works fine, with both syntaxes. If I let the calls run, only the native click event will work. – Martin Fransson Jan 27 '13 at 18:03
1

Because you need to specify the parent selector to taking into account the elements created dynamicaly.

Exemple :

$("body").on('check', '#handler', function() {alert('Handler is working!');})

Here is a good related question : jQuery 1.7 on() and off() methods for dynamic elements

Community
  • 1
  • 1
sdespont
  • 13,915
  • 9
  • 56
  • 97