Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the onClick event triggered twice?

I have the following html:

<span onclick="alert('Boem')">     <button id="test1">test</button> </span> 

When I call the following javascript:

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

The onclick event is triggered twice, while I expect it to just trigger once. Because JQuery should look up in the DOM tree and find only one onclick.

I do not have control of the span, it is generated in a third party tool. I do have control over the button and his parameters.

You can find a JSFiddle example here: http://jsfiddle.net/Voga/v4100zke/

Update

I do not know the contents of the onclick listener of the span. This is also generated by the 3rd party tool. I want the click trigger to execute this onclick like it does now, but only once.

like image 669
Dommicentl Avatar asked Aug 12 '14 12:08

Dommicentl


People also ask

Can a button have 2 Onclick?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

Why Onclick works only once?

onclick event works only once in arctext script. Here is the code in Codepen: http://s.codepen.io/Noureddine/debug/JbbBQX. Well you only execute the random part once. If you want it to execute again, you need to move that logic inside.

What does onclick return false mean?

using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute. In other words, adding return false stops the href from working.

Is it bad to use onclick attribute?

It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.


1 Answers

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

like image 132
Bhushan Kawadkar Avatar answered Sep 20 '22 13:09

Bhushan Kawadkar