Teygeta
Teygeta

Reputation: 58

Button inside a span, both have an event. If I click the button, the span event also starts

<span onClick={'event example 1'}>
  content example 1
  <button onClick={'event example 1'}>
    content example 2
  </button> 
</span>

How can I press the button without also involving the span event? It's possible?

Upvotes: 2

Views: 879

Answers (3)

Anatoliy Kostyuk
Anatoliy Kostyuk

Reputation: 76

there are two extra properties to handle this issue:

  1. event.preventDefault is to prevent the default action of the element.
  2. event.stopPropagation is to stop the event from propagating upwards.

In your handler specify first attribute - event and in html bind the function with event. In this case you need to use stopPropagation.

onClick(function(event){
    event.stopPropagation();
    console.log('button element');
});

Upvotes: 1

Nishant
Nishant

Reputation: 466

Working example. you have to bind event to get access to stop event.stopPropagation()

function spanFunction(e) {
  console.log('spanFunction')
}

function buttonFunction(event) {
  event.stopPropagation()
  console.log('buttonFunction')
}
<span onClick="spanFunction(event)">
  content example 1
  <button onClick="buttonFunction(event)">
    content example 2
  </button> 
</span>

Upvotes: 3

Roma Roma
Roma Roma

Reputation: 67

Events bubble by default. So the target is the element that triggered the event (e.g., the user clicked on).

If u face some ambiguity while stopping the event bubbling via stopPropogation(preferred) u can this structure.

// Dont forget to pass event (e).
if (e.tagName.toLowerCase() === 'button') {
  conosole.log('CLICK');
}

Upvotes: -1

Related Questions