Event Handling: Preventing the Browser's Default Action

JavaScript FAQ | Keyboard & Mouse Events FAQ  

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

from the respective event handler. For example, returning
from an
event handler would prevent the browser from submitting the form; returning
from the
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
your event handler may need to:
  • set
(this is specific to Internet Explorer)
  • call the
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 © 1996-2018, JavascriptFAQ.net.