Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically add listener to ajax created content in jQuery

I am trying to get the html value of a linked clicked. The links are created dynamically with Ajax so I don't think .bind will work and I don't have latest version with .live

$('div#message').click(function() {
  var valueSelected = $(this).html();  // picks up the whole id. I juust want single href!          
  alert(valueSelected);
  return false;
});



<div id="message">
<br/>
<a class="doYouMean" href="#">location A</a>
<br/>
<a class="doYouMean" href="#">location B</a>
<br/>
<a class="doYouMean" href="#">location C</a>
<br/>
<a class="doYouMean" href="#">location D</a>
<br/>
<a class="doYouMean" href="#">location E</a>
<br/>
</div>
like image 916
davidP Avatar asked Dec 02 '22 06:12

davidP


2 Answers

Here's an alternate approach that has not been mentioned:

If you're using jQuery v1.7+ you can use the .on() method to bind an event listener to current HTML as well as HTML that is added in the future:

$('#message a').on('click', function(){
    alert('link clicked!');
});

If you are using an older version of jQuery, it is recommended you use the .delegate() method instead:

$('#message').delegate('a', 'click', function(){
    alert('link clicked!');
});

In summary:

$(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(elements).on(events, selector, data, handler);        // jQuery 1.7+
like image 71
Andrew Avatar answered Dec 03 '22 23:12

Andrew


Apply your handler to just the links, in the callback of the AJAX load.

$('div#message').load( myUrl, function() {
    $('div#message a').click(function() {
       var valueSelected = $(this).html();
       alert(valueSelected);
       return false;
    });
});
like image 40
tvanfosson Avatar answered Dec 04 '22 01:12

tvanfosson