Home > Software design >  how can I prevent the navigation of the anchor tag that is a parent of a button from being executed
how can I prevent the navigation of the anchor tag that is a parent of a button from being executed

Time:08-03

I have a link and I want when I click on any part of the link to do the normal navigation, except when I click on the button(I know this can be achieved using preventDefault()).

I am using voiceover on ios(screen reader), the preventDefault() does not work in this mode when I tap on the button(navigation is done ignoring the preventDefault()), so I would like to find a strategy to keep my navigation when the button has not been tapped, and that when the button is tapped it does not continue with the navigation of the anchor tag.

How can I do this?

function clickedButton(){
 console.log("click");
  alert("click")
}
body,html{
 margin:0px;
 padding:0px;
}

#mainLink{
  margin-top:20px;
  padding:200px;
  border:1px solid red;
}
<a href="www.google.com" id="mainLink">
    <button onclick="clickedButton()">click</button>
</a>

CodePudding user response:

You can use the .stopPropagation() method instead. Then when you click the button the event will not bubble to the parent element.

If you have multiple handlers on the same event then you should use the .stopImmediatePropagation()to stop all the handlers from bubbling the event.

  • Related