Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event for Element nested within a Button

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.

like image 629
Noel Abrahams Avatar asked Jun 17 '12 06:06

Noel Abrahams


People also ask

How do you trigger a click element?

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.

Can a button have two events?

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

What is the event target when clicking the button?

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.

Can we have click event on Div?

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.


1 Answers

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);
});
like image 122
Antoine Combes Avatar answered Oct 14 '22 00:10

Antoine Combes