Here is a simple example of the problem:
<body>
<button id="parent" onclick="alert('parent')">
<span id="child" onclick="alert('child')">Authenticate</span>
</button>
</body>
In Chrome this alerts "child" then "parent", but in IE/FF we only get "Parent".
Clearly this can be fixed in a number of ways (change button to div, remove span etc.), but I wanted to find out if there was a way to make this work (i.e. alert "child") without changing the HTML.
Thanks!
PS: Tried JQuery and that has same behaviour.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.
As @muistooshort said, handling click events inside other click events seems unnatural. I also think you have to rethink your design.
That being said, you can handle a single click event on your main container and then check which element was the source of the click
This would be the way to go, considering your use case, imo:
$('your-button-container').click(function(event){
console.log(event.originalEvent.srcElement);
});
Make the necessary checks on event.originalEvent.srcElement
and act accordingly.
Edit: Not using JQuery, it would go like this:
yourButtonContainer.addEventListener(function(event){
console.log(event.srcElement);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With