How to cancel tag a action?

Asked

Viewed 66 times

0

I need to cancel the anchor action after I send an alert. How do I do this?

I tried with e.eventDefault(). I tried with the window.location to redirect the page to the default and I’m not getting the result I want.

 <script type="text/javascript" defer>
    function alertPages() {  
        alert("Página em contrução")

        const a = document.getElementsByTagName('a')
        a.preventDefault()     
    }   
</script>

<a href="./about.html" onclick="alertPages()">About</a>
<a href="./contact.html" onclick="alertPages()">Contato</a>

In other words, when clicking on the link, show the message not redirect to the page.

  • shouldn’t be: preventDefault()?

  • tested with the preventDefault() and it didn’t work?

  • @Danizavtz of course not, preventDefault is for events, so he would have to add a eventListener for the tag a . Detail that getElementsByTagName returns a Htmlcollection.

  • but I added there, because I’ve just tried with Event Listener too and it wasn’t.

  • getElementsByTagName returns a Htmlcollection, Voce would have to convert and iterate to add a Event Listener.

  • 1

    @Cmtecardeal I am unable to debug, so I asked. sry.

Show 1 more comment

1 answer

0


If what you want is for the page not to follow the normal flow (load the page with the mentioned url), a way to do this would simply change the content of the link if I understood the question correctly:

function alertPages() {
  let a = document.getElementsByTagName('a');

  for (let i = 0; i < a.length; i++) {
    a[i].setAttribute('href', '#');
  }
  alert("Página em contrução");
}
<a href="./about.html" onclick="alertPages()">About</a>
<a href="./contact.html" onclick="alertPages()">Contato</a>

  • @Uelberhenrique Be aware that this code will affect all tags <a> when you click on any of the function alertPages. All tags <a> will have the attribute href changed to #.

  • @That’s right, well remembered, I created the example in the code posted, this code will change all the links of the tags a existing in the document, if you do not want this behavior, just put a class or a id in the tags you want this behavior to occur!

  • 1

    Okay, thank you all very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.