Home > OS >  Nested button in <a> tag with different onClick event
Nested button in <a> tag with different onClick event

Time:07-05

I have a button that is nested in a tag <a>. Tag <a> has a href attribute and button calls a function. When I click on button, button's function is called and then page is redirected to href. But I want to execute only the button's function and not redirected when I click on button.

<a href='/path/to/somewhere' >
   <div >
     <someElements .... />
     <button onClick='someFunction();' >Click</button>
   </div>
</a>

You can suppose that <a> is a card and href is a path to details information. button can be a like or mark button in the card.

CodePudding user response:

You can add the event token to the onClick event and use e.preventDefault() to override the anchor tag event:

function someFunction(e) {
  e.preventDefault()
  console.log('some function executed')
}
<a href='/path/to/somewhere' >
   <div>
     <div>Element 1</div>
     <div>Element 2</div>
     <div>Element 3</div>
     <button onClick='someFunction(event);' >Click Me</button>
   </div>
</a>

It is probably better practices, though, to move the button outside of the anchor tag:

function someFunction() {
  console.log('some function executed')
}
<a href='/path/to/somewhere' >
   <div>
     <div>Element 1</div>
     <div>Element 2</div>
     <div>Element 3</div>
   </div>
</a>
<button onClick='someFunction();' >Click Me</button>

CodePudding user response:

you can add a click event to the a element and check if the target of the event coming from the button execute preventDefault()

document.querySelector('#link').addEventListener('click', (event) => {
  if (event.target === document.querySelector('#button')) {
    console.log('button clicked')
    event.preventDefault()
  }
})
<a href="https://www.google.com" id="link"><button id="button">button</button></a>

  • Related