Cancel <a> tag click event

Asked

Viewed 862 times

2

I need to create a Javascript function that is called when clicking a button and must cancel the click of a tag <a>.

I tried this way:

$("#botao").click(function(){
  $("a").unbind('click')
})

But when you click on the tag it keeps sending to the link of your href attribute. I’ve also tried with .off('click'), but also without success.

After canceling the click I need to be able to return with the click event.

  • 1

    And remove the href by clicking the button, can not be?

  • No because you may need to use this link later. I have to have the possibility to cancel and return the click event

  • 1

    The jQuery has the .one( which only runs once, but I don’t know if that’s what you’re looking for because the question is unclear. You can explain better, show some HTML and give examples of actions and what you expect to happen?

2 answers

2

You can use jQuery to get this result, follow the example.

Click once and remove the link, click again and add the link.

$( ".remover-link" ).click(function() {
  $( ".link" ).each(function( i ) {
    if ($(this).attr("href") == "google.com") {
      $(this).removeAttr( "href" );
    } else {
     $(this).attr( "href", "google.com");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" href="google.com">Google.com</a><br>
<button class="remover-link">Remover Link</button>

I find it a little less complex than using pure javascript.

  • After canceling the click I need to have the possibility to use this link again.

  • I edited the code, take a look again

  • Good answer, but wouldn’t it be better to add another link? For example only

  • I edited again rs. Now it’s much better

  • The problem is that my href url is dynamic, it comes from the backend.

  • And how is this href value added to the <a> element? I know how href is created and added is easier

Show 1 more comment

0


Rersolvi by inserting a data attribute to the link that is true proceeds with get or else makes a false Return.

Browser other questions tagged

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