event.preventDefault method
The event.preventDefault
method
allows you to cancel the browser's default
actions. For example, to make sure that when
clicking on a link there is no transition
to another page or when a button is clicked,
the form is not sent to the server. How to
use: just inside the function that is bound
to the event, call event.preventDefault()
anywhere, where event is the Event
object.
Syntax
event.preventDefault();
Example
Let's make it so that clicking on a link does not follow to another page:
<a href="/" id="elem">link</a>
let elem = document.querySelector('#elem');
elem.addEventListener('click', function(event) {
event.preventDefault();
alert('you can't follow this link!');
});
:
See also
-
the
addEventListener
method
that binds events -
the
removeEventListener
method
that unbinds events