What are the advantages of using jQuery's
$(window).blur(function() { ... })
to attach an event handler versus setting it directly with
window.onblur = function() { ... }
It seems that the latter is less robust because it only supports one blur handler, and when used with other packages, other code might override the window.blur
value with another function. However, couldn't this also happen with the jQuery implementation too, which presumably uses window.blur
as its underlying implementation?
EDIT: Several people have also mentioned the window.addEventListener
alternative, which can be used to add an 'onblur'
event apart from the methods above.
$(window).blur(function() { ... })
Lets you add one or more event handlers.
window.onblur = function() { ... }
Lets you only have one event handler handling the blur event.
The former uses the jQuery's own event handle mechanism. The call to .blur()
will delegate to jQuery.fn.on()
which in turn will delegate to jQuery.event.add
. This add()
method will create it's own handler for the given event type and tell addEventListener()
to call this handler whenever a event of given type is fired. So basically jQuery has it's own way of event handling which relies on addEventListener()
to execute properly.
The latter is just an attribute which can only contain one value so queueing event handlers is impossible.
I wrote a little demonstration to prove this point: http://jsfiddle.net/GnNZm/1/