3

Okay so I want to do the opposite of all the questions in my search results. Most people want to stop jQuery from nesting divs or whatnot because the .load() method ends up being called multiple times.

I want to call .load() every time I click on something. The trouble is that the link with the id I select gets replaced out by the .load(). I have included the same id on a link that's inserted by innerHTML during the first call of .load(). jQuery won't select the newly populated id for subsequent clicks, even though its now in the DOM again.

Main Page:

<div id="#replace_me">
  <p>some stuff</p>
  <a id="click_me">A LINK</a>
</div>

<script type="text/javascript">
   $('#click_me').click(function () {
       $('#replace_me').load('new.html');
   });
</script>

NEW.HTML :

<p>some new stuff that actually is dynamic and changes periodically</p>
<a id="click_me">A LINK</a>

For simplicity's sake I'm not going to go into why I just don't leave that link outside the replaced but the reality is that it needs to go away and come back with the .load() method.

Jimmah
  • 33
  • 5

5 Answers5

2

Use .delegate, which allows you to attach an event handler to an element (#click_me) based on a specific root element (#replace_me):

$("#replace_me").delegate("#click_me", "click", function () {
   $('#replace_me').load('new.html');
});

Example: http://jsfiddle.net/ATyUq/

.delegate is usually a better choice than .live for reasons outlined in this answer.

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
1

You can use the live function:

$('#click_me').live('click', function () {
  $('#replace_me').load('new.html');
});

That will re-bind the event to the newly added element automatically.

Clive
  • 36,918
  • 8
  • 87
  • 113
1

What you're looking for is the live method

$(document).ready(function() {
  $('#click_me').live('click', function() {
    $('#replace_me').load('new.html');
  });
});
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

you need to use .live() because once the new markupo is loaded to the page the original #clickme element doesn't exist anymore.

$('#click_me').live("click", function () {
    $('#replace_me').load('new.html');
});
James Khoury
  • 21,330
  • 4
  • 34
  • 65
0

This doesn't really have much to do with load(), it's that the click handler is attached before the new link exists, so the new link doesn't have and handler attached to it. This is easy to solve with jQuery's live():

$('#click_me').live('click', function () {
    $('#replace_me').load('new.html');
});

http://api.jquery.com/live/

Paul
  • 139,544
  • 27
  • 275
  • 264