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
performs an action when a newly created link is clicked
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With