Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 1.7 on() and off() methods for dynamic elements

Tags:

jQuery 1.7's .on() and .off() methods are supposed to replace .live() and such.

I tried it with a dynamic item:

 $(".myList").on('click', function(e){   alert('hello world');  }); 

This is not working for me for elements added after DOM is loaded.

Is code above a valid example for jQuery 1.7's .on() and .off() methods?

like image 576
David Avatar asked Nov 06 '11 19:11

David


2 Answers

See http://blog.jquery.com/2011/11/03/jquery-1-7-released/ for live() -> on/off() (and other) examples.

This is their example for converting live to on:

$('a').live('click', fn); $(document).on('click', 'a', fn); 

So your example becomes to:

$(document).on('click', '.myList', function(e){   alert('hello world'); }); 
like image 90
biziclop Avatar answered Sep 27 '22 18:09

biziclop


Here is a little example:

http://jsfiddle.net/zzSjK/

<script type="text/javascript">     $(function(){         $(document).on('click','.clickme' , function(e){           addtext()         });         function addtext() {             $('.myList').append('<div class="clickme">click me</div>')         }     }) </script>  <div class="myList">     <div class="clickme">-click-</div> </div> 
like image 39
enloz Avatar answered Sep 27 '22 20:09

enloz