721jQuery’s Live Clicks
Update
Since jQuery 1.7 live() is marked for deprecation and should not be used any more. Use on() instead.
When content is dynamically created by jQuery it is not automatically inserted into the DOM. Therefore, if you dynamically add – for example – a link, and you want to capture a click on this link, it is necessary to use the live() function.it is necessary to use the on() function.
<script type="text/javascript" charset="utf-8"> $(document).ready( function() { $('.container').html('<a href="http://www.trembl.org">click</a>'); }); $('.container > a').click(function(e) { // do things e.preventDefault(); }); </script> <div id="container"> </div
NG. The link is added to the container, but the click function is not called.
// $('.container > a').live('click', function(e) { // pre jQuery 1.7 $(document).on('click', '.container > a', function(e){ // do things e.preventDefault(); });
OK. The link is added to the DOM, and the click function is called.
Yeah.
Of course the same also goes for appended elements:
$("#container").append('<canvas id="track' + trackNumber + '"></canvas>'); // ... // $('#container canvas').live('mousedown', function (e) { $(document).on('click', '#container canvas', function(e){ // pre jQuery 1.7 console.log(this.id); });