Why is the onClick event triggered twice?

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.


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


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


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