mozilla
Your Search Results

    Event.preventDefault()

     

    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="my-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 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.

    Specification