Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created September 21, 2010 17:01
Show Gist options
  • Save elijahmanor/590041 to your computer and use it in GitHub Desktop.
Save elijahmanor/590041 to your computer and use it in GitHub Desktop.
Prevent Default Behavior
// Prevent Default Behavior
// 'return false' stops the default behavior of the event
// and prevents it from bubbling up DOM, which kills
// event delegation and may not be what you indented.
// You might consider using e.preventDefault() or
// e.stopPropagation() instead
//event.preventDefault()
//Event Delegation Friendly
//This is usually what you want
$( "#preventDefault a" ).click(function( e ) {
$( this ).toggleClass( "highlight" );
//Prevents the default behavior (click in this case), but the
//Event will continue to bubble (propagate) up the DOM
e.preventDefault(); //Don't redirect to appendTo.com
});
$( "#preventDefault a" ).click(function( e ) {
alert( "Allows execution of other event handlers bound to object" );
});
$( "#preventDefault" ).click(function( e ) {
alert( "My child has been clicked!" );
});
//event.stopPropagation()
//Kills Event Delegation
$( "#stopPropagation a" ).click(function( e ) {
$( this ).toggleClass( "highlight" );
//Will complete the default behavior (click in this case), but
//Stops the event from bubbling (propagating) up the DOM
e.stopPropagation();
});
$( "#stopPropagation a" ).click(function( e ) {
alert( "Allows execution of other event handlers bound to object" );
});
$( "#stopPropagation" ).click(function( e ) {
alert( "This never shows up!" );
});
//event.stopImmediatePropagation()
//Kills Event Delegation
$( "#stopImmediatePropagation a" ).click(function( e ) {
$( this ).toggleClass( "highlight" );
//Will complete the default behavior (click in this case), but
//Stops the event from bubbling (propagating) up the DOM and
//Prevents execution of other event handlers bound on this object
e.stopImmediatePropagation();
});
$( "#stopImmediatePropagation a" ).click(function( e ) {
alert( "This never shows up!" );
});
$( "#stopImmediatePropagation" ).click(function( e ) {
alert( "This never shows up!" );
});
//return false
//Kills Event Delegation
//Not recommended unless you know what you are doing
$( "#returnFalse a" ).click(function( e ) {
$( this ).toggleClass( "highlight" );
//Prevents the default behavior (click in this case) and
//Stops the event from bubbling (propagating) up the DOM
return false;
});
$( "#returnFalse a" ).click(function( e ) {
alert( "Allows execution of other event handlers bound to object" );
});
$( "#returnFalse" ).click(function( e ) {
alert( "This never shows up!" );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment