jQuery Events by Example

As a supplement to this article, http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/lets look at jQuery event handling by example. [code]
Hello World bar
[/code]

Event bubbling to parent

[code] $(“body” ).click (function() { console.log(“body” ); }) ; $(“p.hello”).click (); >> body;[/code]

Original event target on bubbling

[code] $(“body” ).click (function(event) { console.log($ (event.target).text ()); }); (“p.hello” ).click (); >> Hello World[/code]

‘this’ on event bubbling

[code] $(“body” ).click (function() { console.log($ (this).attr (“class”)) ; }); $ (“p.hello”).click (function() { console. log($(this ).attr (“class”)) ; }).click ();[/code] [code] >> hello >> i-am-the-body[/code]

‘currentTarget’ on event bubbling

[code] $(“body” ).click (function(event) { console.log($ (event.currentTarget).attr (“class”)); });$( “p.hello”).click (function(event) { console.log($ (event.currentTarget).attr(“class”)) ; }).click (); >> hello >> i-am-the-body[/code]

stopPropagation’s effect on event bubbling

[code] $(“body” ).click (function(event) { console.log($ (event.currentTarget).attr (“class”)); });$( “p.hello”).click (function(event) { console.log($ (event.currentTarget).attr(“class”)) ;event. stopPropagation(); }).click (); >> hello[/code]

Event bubbling and multiple events on a single object

[code] $(“body” ).click (function(event) { console.log($ (event.currentTarget).attr (“class”)); });$( “p.hello”).click (function(event) { console.log($ (event.currentTarget).attr(“class”)) ; }).click (function(event) { console.log(“Second!” ); }).click (); >> hello >> Second! >> i-am-the-body[/code]

stopImmediatePropagation’s effect on inner event propagation (multiple events on a single object)

[code] $(“body” ).click (function(event) { console.log($ (event.currentTarget).attr (“class”)); });$( “p.hello”).click (function(event) { console.log($ (event.currentTarget).attr(“class”)) ;event. stopImmediatePropagation() ; }).click (function(event) { console.log(“Second!” ); }).click (); >> hello[/code]

Using custom named events with ‘trigger’

[code] $(“body” ).bind (“customEvent”, function (event) { console. log (event.type); });$(“p.hello”).click (function(event) { console.log(event. type ); $( this ).trigger(“customEvent”); }).click (); >> click >> customEvent[/code]

The context of ‘this’ when an event is passed directly and when called

[code] function eventHandler( ) { console.log ( this instanceof Element ? “yes” : “no”) ; }$(“p.hello” ).click (function(event) { eventHandler(); }).click (eventHandler).click (); >> no >> yes[/code]
America's Best Software Engineers, On-Demand, at an Affordable Price
Surge Forward With Us