Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clone & live function with context parameter jquery 1.4

I have few div HTML elements and i am cloning it with a clone(true) option as i want to copy the events also.

Now the case there are certain click events in my HTML div blocks and while crating events i use context parameter also like

var $block ="<div class='task-create-content' >"+
                 "<div class='task-create-preview'>"+
                      "<div class='items'>" +
                           "<div><input type='text' class='edit wtp'/></div>" +
                           "<div><input type='text' class='edit wtp'/></div>" +
                      "</div>"+
                 "</div>");

$(".wtp", $block).live('click',function() {
     alert("hi");
})

Now , when i clone this block using clone(true), click event doesn't get fire even if i am assigning context parameter.

like image 531
Hunt Avatar asked Sep 02 '10 15:09

Hunt


1 Answers

The .live() method needs the actual selector to match the element against.

Try this:

$(".task-create-content .wtp").live('click',function(){
     alert("hi");
});

It uses that selector at the root of the document to see what exactly received the click event. If there's a match, it fires the handler for that selector.

It seems as though you're assigning handlers directly for newly created elements. If you want to do that, use .bind().

$(".wtp",$block).bind('click',function(){
     alert("hi");
});

...which is the same as doing:

$(".wtp",$block).click(function(){
     alert("hi");
});

EDIT:

The correct A couple of ways to confine a live() event to $block would be to pass $block as a third argument to live().

$(".wtp").live('click',function(){
     alert("hi");
}, $block); // The handler is placed on $block and fired for .wtp elements within

...which is the same as using .delegate()

  // The handler is placed on $block and fired for .wtp elements within
$block.delegate('.wtp', 'click', function(){
     alert("hi");
});

jQuery's .delegate() just nicer packaging for passing the third argument to .live(). It just reorders the arguments, and calls .live().

http://github.com/jquery/jquery/blob/master/src/event.js#L875

like image 174
user113716 Avatar answered Sep 24 '22 13:09

user113716