soubhagya pradhan
soubhagya pradhan

Reputation: 547

Javascript prevent out function call

function alertOuter() {
  alert("outer alert")
}

function alertInner() {
  alert("inner alert")
  return
}
<div onclick="alertOuter()" style="padding:20px;background:red;">
  <h1>Outer</h1>
  <br/>
  <button onclick="alertInner()">Inner</button>
</div>

I have two function calls on onclick event.

I want to prevent alertOuter function when clicking on the button. But, it is calling both the functions when i am clicking on the button.

I wants to prevent that alertOuter funcion when clicking on the button just wants to call alertInner() function

How can I do that?

Upvotes: 0

Views: 47

Answers (2)

Aaron Plocharczyk
Aaron Plocharczyk

Reputation: 2832

I usually like using inline onclick calls as you've done. I find it easier and cleaner to keep track of, and I don't have any issue with it. Here's how you'd use stopPropagation that that way:

div{
  background:red;
  padding:20px;
}
<div onclick="alert('outer');">
  <button onclick="event.stopPropagation();alert('inner');">Click me for inner</button>
</div>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370779

Attach the event listener properly using Javascript so you can see the event parameter, and then call stopPropagation() on the event, so it doesn't bubble up to the containing <div>:

document.querySelector('button').addEventListener('click', (e) => {
  e.stopPropagation();
  console.log('inner');
});
document.querySelector('div').addEventListener('click', () => {
  console.log('outer');
});
<div style="padding:20px;background:red;">
  <h1>Outer</h1>
  <br/>
  <button>Inner</button>
</div>

Best to avoid inline handlers, they have confusing behavior, require global pollution, and are pretty much never required.

Upvotes: 5

Related Questions