tags:

views:

238

answers:

5

I have this code, which gets an clicked div id:

$(document).ready(function(){
    $(".playitem").click(function(){
     pos = this.id;
     alert(pos);
    });
});

And this is html code:

<div class="playitem" id="item-123456">
code here...
</div>

This is how document dynamically loaded:

$("#videoplaylist .left").load("extern1.htm");

Everything is working while this html code is in current html file. But, if I dynamically load an external html document with the same html code and to the same div this jQuery function stops working.

Any advice? Thank you in advance!

+6  A: 

That is because the DOM elements for the new file are not available yet at the time when you are binding a click event handler to them. If there are no elements in the jQuery selector...

$(".playitem").length === 0

And you go to bind a click event handler to those items, jQuery won't error out, it just won't bind the click event handler to anything.

Try using the Live method, This will bind the click event handler to all current and future DOM elements that match the selector.

$(document).ready(function(){
    $(".playitem").live('click', function(){
        pos = this.id;
        alert(pos);
    });
});

Alternatively you can load the new DOM elements and then rebind the click method after those DOM elements are loaded.

Note: you can use the Live method with all of the other event handlers as well (mouseover, keypress, etc.)

Jon Erickson
Jon, thank you very much for such a complete answer!
Jaan Grahv
+3  A: 

Use the live function.

$(document).ready(function(){
    $(".playitem").live("click", function(){
        pos = this.id;
        alert(pos);
    });
});
Patrick McElhaney
...but be sure to understand the differences between live and click around propagation and so on.
DDaviesBrackett
And thank you goes to you Patrick too
Jaan Grahv
A: 

Try using FireBug or the IEDeveloperToolbar to analyze the HTML that the browser is actually using after the load? It may be that the results are different than you expect them to be.

Also, you need to examine the order of events. If the load is happening after the document.ready function, your click event won't attach because the element doesn't exist yet.

John Fisher
A: 

You need to bind the jquery function for onload if you're going to put it inside of that file.

It's currently trying to implement it before it exists, so you have to call it when it gets created.

Sneakyness
A: 

As Sneakyness said, putting the code inside the file will be better as the live method is making the browser slow.

Manu