Visit Mozilla.org

DOM:event.preventDefault

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Cancels the event if it is cancelable, without stopping further propagation of the event.

[edit] Syntax

event.preventDefault()

[edit] Example

Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that happening:

<html>
<head>
<title>preventDefault example</title>

<script type="text/javascript">

function stopDefAction(evt) {
  evt.preventDefault();
}
</script>
</head>

<body>

<p>Please click on the checkbox control.</p>

<form>
<input type="checkbox" onclick="stopDefAction(event);"/>
<label for="checkbox">Checkbox</label>
</form>

</body>
</html>

You can see preventDefault in action here.

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault().

<html>
<head>
<title>preventDefault example</title>

<script type="text/javascript">

function checkName(evt) {
var charCode = evt.charCode;

  if (charCode != 0) {
    if (charCode < 97 || charCode > 122) {
      evt.preventDefault();
      alert("Please use lowecase letters only." + "\n"
            + "charCode: " + charCode + "\n"
      );
    }
  }
}

</script>
</head>

<body>

<p>Please enter your name using lowercase letters only.</p>
<form>
<input type="text" onkeypress="checkName(event);"/>
</form>

</body>
</html>

[edit] Notes

Calling preventDefault during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use event.cancelable to check if the event is cancelable. Calling preventDefault for a non-cancelable event has no effect.

preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.

[edit] Specification

DOM Level 2 Events: preventDefault