Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

This article needs a technical review. How you can help.

 

Summary

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

Syntax

event.preventDefault();

Example

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

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

</head>

<body>

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

<form>
    <input type="checkbox" id="my-checkbox" />
    <label for="my-checkbox">Checkbox</label>
</form>

</body>

<script>
    function stopDefAction(evt) {
        evt.preventDefault();
    }
    document.getElementById('my-checkbox').addEventListener( 'click', stopDefAction, false );
</script>

</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().

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

<script>
function Init () {
    var myTextbox = document.getElementById('my-textbox');
    myTextbox.addEventListener( 'keypress', checkName, false );
}

function checkName(evt) {
    var charCode = evt.charCode;
    if (charCode != 0) {
        if (charCode < 97 || charCode > 122) {
            evt.preventDefault();
            alert(
                "Please use lowercase letters only."
                + "\n" + "charCode: " + charCode + "\n"
            );
        }
    }
} 
</script> 
</head> 
<body onload="Init ()"> 
    <p>Please enter your name using lowercase letters only.</p> 
    <form> 
        <input type="text" id="my-textbox" /> 
    </form> 
</body> 
</html>

Here is the result of the preceding code:

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.

Note: As of Gecko 6.0, calling preventDefault() causes the event.defaultPrevented property's value to become true.

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.

Specifications

Specification Status Comment
DOM
The definition of 'Event.preventDefault()' in that specification.
Living Standard  
DOM4
The definition of 'Event.preventDefault()' in that specification.
Recommendation  
Document Object Model (DOM) Level 2 Events Specification
The definition of 'Event.preventDefault()' in that specification.
Recommendation Initial definition.