what e.preventDefault() method really does?
This question already has an answer here:
Short answer, from http://api.jquery.com/event.preventdefault/
Description: If this method is called, the default action of the event will not be triggered.
Take this example:
$("a").click(function( event ) {
event.preventDefault();
$("<div>")
.append( "default " + event.type + " prevented" )
.appendTo( "#log" );
});
If the hyperlink above is clicked then the browser will not try to redirect the browser (because of the preventDefault()
call), but rather it will instead do the rest of the processing and append data to the div instead.
It's not a jQuery feature, but is part of the Event object passed to Javascript event listeners.
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
When you bind an event listener to a DOM element the Event object is passed as an argument. That listener is executed when that event is triggered, but each event has a default implementation. When you call event.preventDefault
is flags the event object as handled, and the default implementation is skipped.
It's most noticable with <a>
tags when the click
event, because you might want to prevent the link from being followed. But, it also works on things like keyboard input, touch, and so on.