jQuery: How do I use event.preventDefault() with custom events?

If you're asking how to find out whether or not the default has been prevented, use:

event.isDefaultPrevented()

This will return 'true' or 'false' based on whether or not preventDefault() was called.

EDIT: http://api.jquery.com/event.isDefaultPrevented/


trigger() can also take an event object, so if you can create an event object, like so:

var event = jQuery.Event("customEvent");
$(document).trigger(event);

then you can check after the trigger to see if preventDefault() has been called like so:

var prevented = event.isDefaultPrevented();

In case someone needs it, as I did. Important the 2nd constructor-parameter:

Pure JS:

var event = new CustomEvent("close", { "cancelable": true });
// now event listeners can prevent default behavior
element.onclose(event);
// or: element.dispatchEvent(event);

if (!event.defaultPrevented)
    defaultBehavior();

Custom events do not have some default actions that happens .. (they are custom).

On the other hand, if you want to stop the bubbling effect of this event to others then have a look at triggerHandler which does not bubbles up to the hierarchy ..