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

thorn0 picture thorn0 · Feb 9, 2010 · Viewed 9.3k times · Source

How can I know in my triggering code that preventDefault has been called?

$(document).trigger('customEvent', params);
if (/* ??? */)
    doDefaultActions();

Answer

Dave Van den Eynde picture Dave Van den Eynde · Feb 9, 2010

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();