Skip to content Skip to sidebar Skip to footer

Event Handler Triggered Twice Instead Of Once

I am sorry that I have asked two questions in a few minutes. In a html file, I got three child DIV tags in a parent DIV tag:

Solution 1:

This is a case of event bubbling. You can stop event bubbling by giving

e.stopPropagation()

inside the click event handler.

Try

$(function() {
     $("div").click(function(e) {
          var imgID = this.id;
          alert(imgID);
          e.stopPropagation() // will prevent event bubbling
     });
}); 

If you want to bind click event to only child elemets inside the container div then you can give like this

$("#container div").click(function(){
    var imgID = this.id;
    alert(imgID);  
});

Solution 2:

That's because you're binding the event handler to all DIVs. Instead, what you want is bind it only to DIVs within container:

<script type="text/javascript">
$(function() {
     $("#container div").click(function() {
          var imgID = this.id;
          alert(imgID);
     });

}); 
</script>

Post a Comment for "Event Handler Triggered Twice Instead Of Once"