Code with "live" doesn't work. Why?

Hi,

I want to see message when I click on the button “Click”. But I don’t: http://jsfiddle.net/8Observer8/JuEaA/1/

Thank you!

Hi again,

Short answer: because live was deprecated as of jQuery 1.7 and you are using it incorrectly.

To see an alert in your example use .on()

$('.duplicate').on("click", function() {
  alert('clicked');
});

Longer answer:

Prior to jQuery 1.7 .live() was used to attach event handlers to elements that were added to a page dynamically.
For example, if you have two buttons - button 1 displays an alert message, button 2 clones button 1 and inserts it into the DOM.
Something like this:

<button id="button1">Say Hello</button>
<button id="button2">Clone button</button>
<div id="clones"></div>

$("#button1").click(function(){
    alert("Hello!");
});

$("#button2").click(function(){
    $("#button1").clone().appendTo($("#clones"));
});

Button one will alert “Hello!” when you click it, but none of the cloned buttons will exhibit this behaviour, as they were not present when the DOM was rendered.

To get around this, you used .live():

$("#button1").live("click", function(){
    alert("Hello!");
});

Which would attach the behaviour to button one and all of its clones.

Now that .live() has been deprecated, we prefer to use .on(), specifying the element which can be added as a second parameter:

$("body").on("click", "#button1", function(){
    alert("Hello!");
});

Here’s a Fiddle.

Hope that helps.

Yes, I wanted to clone buttons. Thanks you for you help :slight_smile: