21

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?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
David
  • 325
  • 1
  • 3
  • 11

3 Answers3

33

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');
});
biziclop
  • 14,466
  • 3
  • 49
  • 65
  • 4
    Something to realize though. on() does not work with dynamically created elements that are appended to the body AND have have a negative z-index. For whatever reason, the click never traverses past the body containing element. The body tag will keep catching all clicks. Even if you make the body a z-index lower than the element being added to the DOM. HOWEVER live() DOES have the power to target these negatively indexed items even though on() cannot. – Alex May 25 '12 at 14:01
  • 1
    @Alex why would you need to dynamically create elements with negative z-index ? – Omu Sep 08 '12 at 21:06
  • 1
    and most importantly as of jQuery version 1.9.0 - live() method is no longer available. – Spencer Mark Jan 21 '13 at 21:57
4

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>
enloz
  • 5,704
  • 9
  • 37
  • 56
2

"Bind" with:

$(document).on('click','.myDiv',function(){ ... });

And "unbind" with:

$(document).off('click','.myDiv');
Andri
  • 553
  • 4
  • 20