partho
partho

Reputation: 1084

How to prevent javascript bubbling

I am talking about Jquery. Say, I have a button, I clicked it and a new div is dynamically created. I clicked again and another div is created. This way I created 3 div.

Each of the newly created div also dynamically creates a button, clicking which I want to get alert('something')

Problem is that, when I click button of 1st div(newly created div) I get the alert 3 times, When I click button of 2nd div(newly created div), I get alert 2 times. For every one click I want to get alert only once. But I am facing Javascript bubbling*

My Javascript and HTML codes:

$("#btn11").click(function(){
    var nw="<div class='product_input'><input type='text'/><br/>";
    nw+="<button type='button' class='btn12'>Add category</button>";
    nw+="</div>";
    $("#apnd1").append(nw);

    $(".btn12").click(function(){
      alert("jhfj");
    });
  });
<div id="apnd1"></div>
<button type="button" id="btn11">Add product</button>

How to get rid of this?

Upvotes: 0

Views: 61

Answers (2)

stanze
stanze

Reputation: 2480

Use event delegation for the same, Demo

$(document).ready(function(){
        $("#btn11").click(function(){
            var nw="<div class='product_input'><input type='text'/><br/>";
            nw+="<button type='button' class='btn12'>Add category</button>";
            nw+="</div>";
            $("#apnd1").append(nw);            
        });
    $(document).on('click', ".btn12", function(){
                alert("jhfj");
            });
});

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Dont bind the events inside another evens. You can bind it outside. Since it is dynamically created, you need to use delegate to bind the events. Then you will not get multiple alerts

$("#btn11").click(function() {
    var nw = "<div class='product_input'><input type='text'/><br/>";
    nw += "<button type='button' class='btn12'>Add category</button>";
    nw += "</div>";
    $("#apnd1").append(nw);
});
$("#apnd1").on("click", ".btn12", function() {
    alert("jhfj");
});

Fiddle

Upvotes: 4

Related Questions