Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent default link action with addeventlistener

Tags:

javascript

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

like image 333
machiine Avatar asked Dec 15 '22 02:12

machiine


1 Answers

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>
like image 180
Scott Marcus Avatar answered Dec 17 '22 01:12

Scott Marcus