machiine machiine - 12 days ago 7
Javascript Question

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?

Answer
var a = document.getElementById(link);
a.addEventListener('click',function(e){
   e.preventDefault(); // Cancel the native event
   e.stopPropagation();// Don't bubble/capture the event
}, false);
Comments