Skip to content Skip to sidebar Skip to footer

Why Is The Onclick Event Triggered Twice?

I have the following html: When I call the following javascript: $('#test1').tr

Solution 1:

It is calling twice because button is inside a span and span has onclick="alert('Boem')", hence when you trigger click on button then it shows alert and same click event propagate to span and shows alert once again.

you need to stop default behaviour of button using below code :

$(function(){
$('#test1').click(function(e){e.preventDefault();}).click();
});

Demo

Solution 2:

I was also getting a similar issue where I had to download a pdf which was downloading twice. I used jQuery's stopImmediatePropagation method.

$( "#test1" ).on("click", function(e) {
     e.stopImmediatePropagation();
});

$('#test1').trigger('click');

stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing. Refer here for more details.

Solution 3:

to stop event propagation use :stopPropagation

$( "#test1" ).on( "click", function(ev) {
    ev.stopPropagation();
});
$('#test1').trigger('click');

Please note, in order events are assigned in DOM.

DEMO

Solution 4:

Bubbling. The click event on the child also happens on the parent (span).

Solution 5:

This thread will help answer the 'why' of it.

A better way would be to just assign a click handler to the element so as to keep your Javascript abstracted out of the HTML:

http://jsfiddle.net/v4100zke/3/

$('#test1').click(function() {
    alert('Boem')
});

Hope that helps.

Post a Comment for "Why Is The Onclick Event Triggered Twice?"