Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent default action for an Anchor tag using Javascript?

Tags:

javascript

dom

I'm trying to prevent default action on an anchor ("a") tag. In my scenario few lines of html are rendered on the fly using ajax (after a form is submitted) and I want to add an event listener that

  1. performs an action when a newly created link is clicked

  2. prevent the browser from opening that link.

Here's what I'm writing:

a = document.getElementById("new_link");
a.addEventListener("click",function(){alert("preform action");
                                      return false;},false);

I have also tried:

a.addEventListener("click",function(e){e.preventDefault(); alert("preform action");});

When I click on the link "a" it shows the alert message but still opens the "href" link where as I want it to show the message and then stop.

Both methods show alerts if attached to an pre-existing link but do not work when attached to newly inserted links (via ajax).. which is what I need to do.

Any help/suggestions.

Thanks.

like image 279
Anwar Avatar asked Dec 04 '22 09:12

Anwar


1 Answers

Reviving an old topic, but I wanted to provide an option that didn't rely on jQuery.

a = document.getElementById("new_link");
a.addEventListener("click",function(){
     alert("preform action");
     window.event.preventDefault();
},false);
like image 190
Jason Hazel Avatar answered May 14 '23 04:05

Jason Hazel