Tomer Lichtash
Tomer Lichtash

Reputation: 9252

Script goes ghost when dynamic content is loaded

After loading a PHP template (using jQuery's load function), this simple script won't make the DIV go away:

$("#trigger").click(function(event){
$("#removeThisDIV").hide();

The HTML bit:

<p id="trigger">X</p>

Tried to remove other DIVs, before the load -- it works just fine. After the load, the script went dead. Ideas?

Thanks.

Upvotes: 1

Views: 221

Answers (2)

Mathew
Mathew

Reputation: 8279

As karim79 mentions, the div you want to use as the trigger wasn't part of the DOM when you assigned the click function, so it doesn't have the needed functionality. Of course, you could simply place the js in the PHP template itself;

<p id="trigger" onclick="$('#removeThisDIV').hide();">X</p>

Make sure to include jquery above this element though, or it'll throw a "$ not recognised" error.

Upvotes: 1

karim79
karim79

Reputation: 342625

Use event delegation with live, as after you call $.load the newly injected elements will not have the click event handler bound to them:

$("#trigger").live("click",function(event){
    $("#removeThisDIV").hide();
});

Alternatively, use $.load's callback:

$('#blah').load('some.html', function() {
    $("#trigger").click(function() {
        $("#removeThisDIV").hide();
    });
});

For live to work, you will need to be using jQuery 1.3 or greater. Hope that helped.

Upvotes: 2

Related Questions