event.preventDefault()S2C Home « Objects « event.preventDefault()

Event prevent default action method.

Description

The event.preventDefault() Event object method when prevents an events default action from triggering.

  • When an event reaches an element, all handlers bound to that event type for the element are fired. If multiple handlers are registered for the element, they will always execute in the order in which they were bound. When all handlers have finished executing, the event continues along the normal event propagation path.
    • A handler can prevent the event from bubbling further up the document tree, thus preventing handlers on those elements from running, by calling the event.stopPropagation() method.
    • If other handlers are attached to the current element these will run however. This can be prevented by calling the event.stopImmediatePropagation() method.
    • To cancel any default action that the browser may have for this event, call the event.preventDefault() method.
    • Returning false from an event handler or calling an event handler with the false parameter, as an example
      ( $('aSelector').on('anEventType', false); ) will automatically call the event.stopPropagation() and event.preventDefault() methods on it.

Syntax

Signature Description
event.preventDefault()Prevents an events default action from triggering.

Parameters

None.

Return

An undefined object.

event.preventDefault() ExampleTop

Prevents an events default action from triggering.

In the example below we show a new message in the 'div' element with an id of 'div10' whenever the mouse is clicked on this anchor 'a' element within this element.

We are stopping the default action for the element, which in this case is redirecting to the link, from occuring by calling the event.preventDefault() Event object method on the element.



$(function(){
  $('#div10 a').on('click', function(event) {
     event.preventDefault();
     $('#div10').append('Has event.preventDefault() been called on this event object? ' 
                       + event.isDefaultPrevented() + '<br/>');
  });
});

div10. Click this link.  Top.