Event is firing Two times - javascript

Hi I am binding onclick event to parent as well as child (same method). Event is getting fired two times How to avoid this?
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId" onclick="javascript:somemethod()"></button>
</div>
Onclick of Div the event is getting fired two times.

Try:
<button id="childId" onclick="javascript:somemethod(event)"></button>
JS code
function somemethod(event){
event.stopPropagation();
}

The reason that the onclick event is showing twice, is because there is something called event bubbling in JavaScript.
Take a look at the following:
This image shows that, if the <img> was clicked, the event would "bubble" up to the <p> tag, then to the <div>, then to the rest of the document. If there was an onclick event on the <p> tag, and even if the <p> tag was not clicked (but the <img> was), the event would necessarily "bubble" all the way up the DOM, and would still continue when an event was fired on the <p> tag (in other words, if you also had an onclick event on the <div>, then that would fire as well.
So what you should do is this:
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId"></button>
</div>
In other words, as I explained above, you wouldn't need the extra onclick event handler in your button anymore, because when your button is clicked, the event bubbles up to the parent div, which would fire that event.
If you want to use your original HTML code, that's fine as well - just add this:
function somemethod(evt) { // the method you run
// some code
evt.stopPropagation(); // stops bubbling
}
This effectively stops the event from bubbling up your DOM tree.

It is getting called twice because you are calling it twice, i.e. once in the div click and once in the button click. the button is already inside the div.
<div id="sparentId" onclick="javascript:somemethod()" >
<button id="childId" onclick="javascript:somemethod()"></button>
</div>
try
<div id="sparentId">
<button id="childId" onclick="javascript:somemethod()">Click Me</button>
</div>

use
event.stopImmediatePropagation()

Related

Prevent or handle click event on child and parent tags in same section

I have developed the onclick functionality which performs specific operation regardless of clicks of tags, it seems like when I click on child tag or child click event fires its relevant parent click event automatically fired.
Need to prevent the event or handle event related to a specific tag is clicked.
What I want is when parent tag is clicked then only parent onclick function should fire, in case of child tag is clicked then only a child's onclick event should be fired.
The same functionality developed using the react app(reactjs) but the result is the same, can not able to handle the onclick event separately.
<div onClick="console.log('div tag click event fired')">
<h1 onClick="console.log('h1 tag click event fired')">This is a Heading</h1>
<p onClick="console.log('p tag click event fired')">This is a paragraph.</p>
<div>
using Event stop propagation keeps the event from bubbling any further up into the DOM. here is sample
use event.stopPropogation() to prevent event from bubbling to parent.
<div onClick="console.log('div tag click event fired')">
<h1 onClick="console.log('h1 clicked');event.stopPropagation();">This is a Heading</h1>
<p onClick="console.log('p tag click event fired'); event.stopPropagation();">This is a paragraph.</p>
<div>
with react it's slightly different from vanilla js, you can check it here:https://reactjs.org/docs/handling-events.html

JavaScript click and focus event order

I have a span inside a div, the div has an onfocus() event, while the span has an onclick() like so:
<div id="divEl" tabindex="0">
<span id="spanEl"></span>
</div>
https://jsfiddle.net/nyva4jrc/
When clicking on the span, the div.focus event fires first, despite the fact that, by my understanding, it should only fire after the click has bubbled up to the div.
Is there a a reason for this, and is the event firing order in this situation defined? Also is there any reference for the order in which dissimilar events fire?

button click event triggering wrong event handler

I have a div display some titles of music which is clickable. When you click it it will show some more detail information. Then I also have a button in the clickable div. When I click the button. It won't call the function of the button but the function of the div? Is there a way to solve this? Thank you!
$("#myComList").append("<div id="+comListID+" class=listDiv> <p class=comTitle><? echo $row["compositionTitle"] ?>(<?echo $row["year"]?>)</p><button id="+comListID+"btn class=addNewArrBtn>Add new Arrangement</button> <p class=comOri>BY <? echo $row["OrigComposer"] ?></p> </div>");
$('#'+comListID).click(function() {
$(this).find("li").slideToggle('slow', function() {
});
$("#"+comListID+"btn").click(function(){
addNewArr(comListID);
});
It's called 'bubbling'. The button is inside the div so it's executing button then up the chain to div. Add event.stopPropagation() inside the button function.
$("#"+comListID+"btn").click(function(event){
event.stopPropagation();
addNewArr(comListID);
});
From jQuery documentation:
By default, most events bubble up from the original event target to
the document element. At each element along the way,
jQuery calls any matching event handlers that have been attached.
A handler can prevent the event from bubbling further up the document
tree (and thus prevent handlers on those elements from running) by
calling event.stopPropagation(). Any other handlers attached on the
current element will run however. To prevent that, call
event.stopImmediatePropagation(). (Event handlers bound to an element
are called in the same order that they were bound.)
http://api.jquery.com/on/
So you'd call event.stopPropagation() inside the button click handler, as to stop the div event from firing.
I believe I understand your question without seeing the code. The problem it sounds like stems from the click event bubbling or propagating up. Below is a sample of code to try and a link to a fiddle for you to test:
<div id="testDiv" onclick="alert('Stop Clicking Me!');">
<button type="button" onclick="function(e) { alert('You hit the button!'); e.stopPropagation(); }">Click Me!</button>
</div>
In this function, the:
e.stopPropagation();
prevents the click event from filtering up to its parent container (in this case "testDiv") and triggering its click event as well. You can test it and see for yourself in the jsfiddle below:
Test Fiddle
EDIT:
In your case:
$("#"+comListID+"btn").click(function(e){
addNewArr(comListID);
e.stopPropagation();
});
add the event parameter to the click function and stop it from propagating to the parent.
Hope this helps.

Issue regarding live event

I was just reading http://api.jquery.com/event.stopPropagation/
Since the .live() method handles
events once they have propagated to
the top of the document, it is not
possible to stop propagation of live
events
I was a bit confused with this statement, Can someone please explain me the same with some example?
Live method binds a handler to the document, and identifies which element triggered the event from the event.target property.
So the actual handler is at the top (in terms of hierarchy).
The stopPropagation stops the bubbling from going up the DOM hierarchy, but since the handler is at the top already (in the .live case) there is no upper place to bubble to ..
example attempt ..
- document
- div
- link
you bind a click event handler to the link (with the bind or click method).
When you click the link, the handler is triggered, but in addition the click event goes up the DOM until it reaches the document, and will also trigger click handlers bound to the div and document. (unless you use the .stopPropagation)
Alternatively if you use the .live method to bind the event handler, it will be bound to the document. If you now click the link, the event (which will not fire right away, since no handler is bound to it) will naturally go up the DOM (triggering the click handlers it encounters). Once it reaches the document it will trigger our own handler. But there is no upper to go, so the stopPropagation is useless at this point.
HTML:
<div id="outer">
<div id="inner">
<span>.live() version</span>
</div>
</div>
<div id="outer2">
<div id="inner2">
<span>.delegate() version</span>
</div>
</div>
JS:
$(function(){
$('#inner2').delegate('span', 'click', function(e){
e.stopPropagation(); // indeed, no alert!
});
$('span').live('click', function(e){
e.stopPropagation();
// we would expect the propagation to stop here, so no alert, right?
});
$('#outer2, #outer').click(function(){ alert("Don't reach me!"); });
});
Example: http://jsfiddle.net/knr3v/2/
.live() only does its magic once the event has already bubbled, so stopping the event from propagating is useless - it's too late, it has already reached the top of the tree and propagated...

prevent browser from generating double click event

I have two overlapping div elements in my web app.
On the underlying div an event is registered on double click.
On the div that lies above the other div a event is registered on click that hides the div.
The problem is that if I double click on the above div element it is hidden after the first click BUT the second click causes the double click event on the underlying div to fire - how can I prevent that?
Mixing "click" and "double-click" is going to be problematic at best. However, in this case things might get better if you just ensure that your handler for the "click" event (the event that hides the element) returns false to the browser.
How to do that depends on how your handler is registered. If it's like this:
<div onclick='hideMe();'>
then you'd change that to
<div onclick='hideMe(); return false'>
If you're using some framework or some other means of attaching the handler, then just having the handler function return false should do it.

Categories