<a id="link" href="example.com">test</a>
var a = document.getElementById(link);
a.addEventListener('click',function(e){
//code
}, false);
How can I prevent the link action to go to example.com?
Event handlers that are registered with .addEventListener()
(the modern, standard way to register events), are automatically passed a reference to the event
object that represents the event that triggered the handler in the first place. This event
object has many properties, but the following two are what you are looking for:
event.preventDefault()
event.stopPropagation()
document.getElementById("link").addEventListener('click',function(e){
e.preventDefault(); // Cancel the native event
e.stopPropagation();// Don't bubble/capture the event any further
});
<a id="link" href="example.com">test</a>
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