Kirzilla
Kirzilla

Reputation: 16596

Bind click and live click

Why this code works (see code at jsfiddle)

$(document).ready(function() {
    var html = '<div><a href="javascript:">click me</a></div>';
    var $div = $(html);
    $div.find('a').bind('click', function() { //attention on bind
        alert('Hi');
    });
    $('#test').append($div);
});

but the same code with .bind('click' replaced with .live('click' is not working? Why?

Thank you.

Upvotes: 4

Views: 1467

Answers (5)

fmalamitsas
fmalamitsas

Reputation: 56

Great article on [differences between jQuery .bind() vs .live() vs .delegate() vs .on() : http://www.elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

Upvotes: 0

dst17
dst17

Reputation: 11

You can use .bind() on a specific html element (here : $div > a) but the .live() function is different : it applies to elements of the same kind (like $("div > a")).

So you can change $div.find('a').bind('click', in $('div > a').live('click',

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

You can use delegate instead like this:

var $div = $('<div><a href="javascript:">click me</a></div>');
$div.delegate('a', 'click', function() {
    alert('Hi');
});
$('#test').append($div);

JS Fiddle Example

Upvotes: 3

Igor Dymov
Igor Dymov

Reputation: 16460

jQuery documentation says:

DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector.

So if you change $div.find('a').bind('click' to $('#test a').live('click' it would work.

Upvotes: 5

Bas Slagter
Bas Slagter

Reputation: 9929

Maybe you should not replace $(document).ready with .live('click') by nest it. The cause of your problem may be that the document is not fully loaded yet, so the binding is not working.

So try something like:

$(document).ready(function() {
  $('mybutton').live('click', function(){ ... });
}

Upvotes: 0

Related Questions