machiine
machiine

Reputation: 63

prevent default link action with addeventlistener

<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?

Upvotes: 5

Views: 18797

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65853

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:

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>

Upvotes: 16

Related Questions