jQuery Event’s missing function – cancelEvent

Well, it’s not officially a missing function according to the W3C spec, but it is a function that I have found very useful over the past couple of years of DOM work.  The missing useful function is, as I call it, cancelEvent.  According to the level 2 spec, there are two main functions that can be called on an event (Level 3 has more), preventDefault and stopPropagation.  preventDefault prevents the default action of the event, for the element the handler is registered on.  stopPropagation keeps the event from propagating (bubbling).  cancelEvent is a combination of the two, i.e.:

function cancelEvent( event ) {
    event.preventDefault();
    event.stopPropagation();
}

Where is this useful? Anywhere you want to prevent the default action from happening and you want to stop the event from bubbling. ;) DOH. My particular use has been buttons of all sorts where I do not want a link to open, nor do I want any click handlers further up the DOM being called.

My patch to jQuery (currently working off of version 1.6.3):
find the line:

        isImmediatePropagationStopped: returnFalse

and overwrite that with:

	isImmediatePropagationStopped: returnFalse,
	cancelEvent: function(){
		this.preventDefault(); this.stopPropagation();
	}

To use in your event handlers that take the event as an input parameter:

function foo( event ) {
   event.cancelEvent();
}

Simple.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Google Buzz Post to Reddit Post to Slashdot Post to StumbleUpon Post to Technorati

Comments are closed.