0

I have a page with a left nav which has two links and a main div. The main div is updated with content from the server whenever user clicks a link in the left nav. I use pjax for this.

When user initially comes to this page, the main div has a link with id somelink that shows an alert box when the user clicks the hyperlink. This is accomplished by this code:

   $(document).ready(function() { 
    .....
    $('#somelink').click(function (event){
       alert("here");
    });
     ....
   });

When the second link on the nav bar is clicked, I load content from the server and update the main div. When user clicks first link, again I load content from the server and update the main div. However, this time when I click somelink nothing happens. Its as if jQuery isn't able to detect that there is a link with id somelink because it was loaded via ajax.

Is there a way to overcome this?

Anthony
  • 27,490
  • 32
  • 129
  • 238

2 Answers2

4

You need to use .on and delegate the click handler to a higher level element that isn't being replaced since it's loaded with AJAX.

$(main).on('click', '#somelink', function() {
    alert("here");
});

The reason being that when you do $('#somelink'), it goes through the DOM and finds each one as it is. So, when you remove it by replacing, you either need to add that again or use .on

tvanfosson
  • 490,224
  • 93
  • 683
  • 780
kalley
  • 16,448
  • 2
  • 34
  • 35
0

You've replaced the elements and so the attached events. You need to add them differently to make them automatically available after dom updates.

Try the on function:

$('#somelink').on('click', function() {});

Older jQuery versions do the with the "live" function and with even more older version you have to bind your events again after every dom update.

Lord Midi
  • 645
  • 1
  • 7
  • 23