Home > front end >  how to prevent all <a> navigation when a button inside it is clicked? example: <a href=&quo
how to prevent all <a> navigation when a button inside it is clicked? example: <a href=&quo

Time:08-03

I have a constraint in my actual code, but this question may help me with my problem, it is similar to this.

I know it's a bad idea to have 2 embedded anchor tags, but it's a restriction of a code that I can't change in a real project, but I'm excited to learn some way to have a solution to the problem I present

I have an anchor tag that is a parent of another anchor tag, and this last anchor tag has a button. I want that when I click exclusively on this button, prevent the execution of the navigation of the anchor tag and execute the function of the button.

but I want the navigation to proceed normally if you click on any other element than the button.

How can I do it?

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

#mainLink{
  border:1px solid red;
}

#secondaryLink{
  border:1px solid blue;
 padding:20px;
}
<a href="www.google.com" id="mainLink">
   go to google
    <a href="www.wikipedia.com" id="secondaryLink">
        go to wikipedia
        <button onclick="clickedButton(event)">click</button>
    </a>
</a>

CodePudding user response:

Here is a dirty solution.

Loop through all of the buttons wrapped by an anchor and replace the anchor tag with the button with a new class added. And add a click handler to the body and look for clicks on the element with that class.

And hide the extra top most anchor via CSS.

document.addEventListener("click", function(e) {
  if (e.target.className.indexOf("btnClick") > -1) {
    console.log("clicked")
  }
});

let linkBTNs = document.querySelectorAll("a > button");

linkBTNs.forEach(function(btn) {
  btn.className = "btnClick";
  btn.parentNode.replaceWith(btn)
});
.btnClick {
  color: red;
}

html,body{height:100%;}
#mainLink{display:none}
<a href="www.google.com" id="mainLink">
   go to google
    <a href="www.wikipedia.com" id="secondaryLink">
        go to wikipedia
        <button>click</button>
    </a>
</a>

CodePudding user response:

<button onclick="clickedButton(event)">click</button>


<script>
clickedButton = function(e){
console.log("click");
[...] Any code you want
e.preventDefault();
</script>

"The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL" - w3school

  • Related