Skip to content

Instantly share code, notes, and snippets.

@zhuzhuaicoding
Forked from elijahmanor/gist:590041
Created December 5, 2011 10:07
Show Gist options
  • Save zhuzhuaicoding/1433097 to your computer and use it in GitHub Desktop.
Save zhuzhuaicoding/1433097 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!" );
});
@zhuzhuaicoding
Copy link
Author

nice tips...thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment