SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Zealot 8Observer8's Avatar
    Join Date
    Jul 2013
    Location
    Russia
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,312
    Mentioned
    177 Post(s)
    Tagged
    8 Thread(s)
    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()

    Code JavaScript:
    $('.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:

    Code:
    <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():

    Code JavaScript:
    $("#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:

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

    Here's a Fiddle.

    Hope that helps.

  3. #3
    SitePoint Zealot 8Observer8's Avatar
    Join Date
    Jul 2013
    Location
    Russia
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, I wanted to clone buttons. Thanks you for you help


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •