Imad
Imad

Reputation: 7490

JQuery.live() not working properly

I know live was deprecated in version 1.7 and removed in 1.9 and its is not recommended anymore. But still, as I am preparing for interview machine test and hence I am trying to get difference between live and on. Document says

Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.

hence I tried this. Markup:

<div>
    <h1>
        <a href="#">
            <span>Hello</span>
        </a>
    </h1>
</div>

Script:

$(document).ready(function () {
        $('span').live("click",function () {
            alert('span');
        });
        $('a').click(function () {
            alert('span a');
        });
        $('h1').click(function () {
            alert('span a h1');
            event.stopPropagation();
        });
        $('div').click(function () {
            alert('span a h1 div');
        });
    });

I am using Jquery version 1.7, in which both live and on exist.

Whats happening:

  1. live of span is not getting called, instead it calls directly click of a.
  2. If I remove all other events than live then it is getting called.
  3. As doc says, it is doing exactly opposite, i.e it's stopping event bubbling if I use event.stopPropagation();

JSFiddle

Upvotes: 0

Views: 88

Answers (1)

t.niese
t.niese

Reputation: 40842

Event handlers attached by live are attached always to the document. If you call event.stopPropagation in a callback of live then this event is already bubbled up to the document, so it will have no effect to directly attached event handlers.

Your event.stopPropagation() is called when the event reaches, the h1element, so it will never reach the document where the live event handler is attached.

With on you can create all type of event handling jQuery supports. If you look at the source of jQuery, you can see that in 1.7 the live function just maps to on:

live: function( types, data, fn ) {
   jQuery( this.context ).on( types, this.selector, data, fn );
   return this;
}

The reason for live to be removed was to make the api clearer and more logical to when event happens and where they are catched.

EDIT

Your DOM and the place where your event handlers are attached to:

 document    $('span').live("click") **not called**  (equal to: $(document).on('click', 'span') ) 
    |
   div       $('div').click() **not called**
    |
    h1       $('h1').click() + event.stopPropagation() **the propagation (bubbling)  is stopped here not reaching the document**
    |
    a        $('a').click()
    |
   span      **event happens here and bubbles up**

Upvotes: 2

Related Questions