Question

hi guys need little bit help..

i know .live is no more working in jQuery v1.9 is there any alternative that my below function get back working i try .on() and .bind() but did not succeed. here is fiddle

HTML

<div id="container">
    <p>There are 0 boxes</p>
    <a href="#" class="more">Add more +</a>
</div>

jQuery

$(".more").click(function() {
    $("#container").append("<div class='box'><a href='#'>x</a></div>");
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
    if(count>2){
        $(".more").hide();
    }

});

$(".box a").live("click", function() {
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});
Was it helpful?

Solution 2

Your script code should be this;

$(".more").click(function() {
  $("#container").append("<div class='box'><a href='#'>x</a></div>");
  var count = $(".box").length;
  $("p").text("There are " + count + " boxes.");
    if(count>2)
     {
       $(".more").hide();
     }

  $(".box a").click(function() {
  $(this).parent().remove();
  var count = $(".box").length;
  $("p").text("There are " + count + " boxes.");
    if(count<3)
     {
      $(".more").show();
     }
  });   
});

here is fiddle

OTHER TIPS

Use delegation of events for elements which are added dynamically:

http://jsfiddle.net/89wTX/11/

$(".more").on('click', function() {
    $("#container").append("<div class='box'><a href='#'>x</a></div>");
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
    if(count>2){
        $(".more").hide();
    }

});

$("#container").on("click", '.box a', function() {
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});

When you just use on without delegation it attaches listeners once to existing elements. When you add new elements(boxes in your case) they have no listeners attached.

TRy this http://jsfiddle.net/devmgs/89wTX/9/

$(document).on("click",".box a", function() {
    console.log("removeing");
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});

Use on :

$(".box").on("click","a", function() {...})
$(".box").on("click","a", function() {
   ....
});

reference on

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top