Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

$(document).trigger('customEvent', params); if (/* ??? */)     doDefaultActions(); 
like image 738
thorn0 Avatar asked Feb 09 '10 14:02

thorn0


People also ask

What is event preventDefault () in jQuery?

The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.

How do you use event preventDefault?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What's the difference between event preventDefault () and event stopPropagation () methods?

preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree.

What is the opposite of event preventDefault ()?

There is no opposite method of event. preventDefault() to understand why you first have to look into what event. preventDefault() does when you call it. Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution.


2 Answers

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(); 
like image 165
Dave Van den Eynde Avatar answered Sep 20 '22 01:09

Dave Van den Eynde


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/

like image 27
user113716 Avatar answered Sep 20 '22 01:09

user113716