Event Handling:
|
![]() |
Question: How do I prevent the browser's default action in a JavaScript event handler?
Answer:
In the early days of JavaScript, to prevent the default response to an event,
you could simply refurn false
from the respective event handler.
For example, returning false
from an onsubmit
event handler would prevent the browser from submitting the form;
returning false
from the onclick
event handler of a link would prevent the browser from following the link.
In most modern browsers, behavior like the above still works;
however, now there are many more supported event types, and
the actual behavior may depend on the browser and the event type.
Therefore, to prevent the browser's default action, in addition to returning false
your event handler may need to:
event.returnValue
to false
(this is specific to Internet Explorer)
preventDefault()
method (this works in most browsers other than IE)
All of the above techniques can be combined in a cross-browser function:
function cancelDefaultAction(e) { var evt = e ? e:window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; return false; } // Call the cancelDefaultAction() function // to prevent the default browser response: function handleEvent(e) { var evt = e ? e:window.event; // event handler code goes here return cancelDefaultAction(evt); }
See also:
Copyright © 1999-2011, JavaScripter.net.