event.preventDefault

Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Example
  4. 4. Notes
  5. 5. Specification
Table of contents
  1. 1. Summary
  2. 2. Syntax
  3. 3. Example
  4. 4. Notes
  5. 5. Specification

« Gecko DOM Reference

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 happening:

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

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

<body>

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

<form>
<input type="checkbox" id="my-checkbox" />
<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().

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

<script>
    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"
                );
            }
        }
    }
    
    document.getElementById('my-textbox').addEventListener(
        'keypress', stopDefAction, false
    );
</script>
</head>

<body>

<p>Please enter your name using lowercase letters only.</p>
<form>
<input type="text" id="my-textbox" />
</form>

</body>
</html>

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.

Gecko 6.0 note
(Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3)

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.

Tags (3)

Edit tags

Attachments (0)

 

Attach file