jQuery vs DOM return false
What does return false
do inside a JavaScript event handler? What does it do in a jQuery event handler? Are they the same thing?
The short answer is “no”. return false
in a native JavaScript event handler prevents the default behaviour of the event. It’s the equivalent of event.preventDefault()
. This is the same for DOM level 0 event handlers like this:
element.onclick = function () { };
and DOM level 2 event handlers like this:
element.addEventListener('click', function () {});
return false
in jQuery, on the other hand, will stop the default behaviour and stop the event propagating. This can be seen in the jQuery source:
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
If the return value of the handler is false
, jQuery will call preventDefault
and stopPropagation
on the event object.
I’ve made a fiddle to demonstrate this behaviour, showing what return false
does with DOM level 0 and level 2 handlers, and with jQuery handlers.