Bind Multiple Events Simultaneously with jQuery
Tuesday, June 5, 2007
It is sometimes necessary to bind two or more events to an element that utilize the same function. Using jQuery it might look something like this (where ‘fn’ is a function reference).
$("a")
.bind("focus", fn)
.bind("mouseover", fn);
That isn’t terrible but it would be nice if we could write it like this.
$("a").bind("focus mouseover", fn);
Well, now we can! I just checked in an extension to the jQuery plugins repository that adds this functionality. It is pretty small and if you use this pattern often, then save yourself some typing and get this extension! You can grab the source code from SVN or from here. You can find a test/example page here. This new syntax also applies to the one and unbind methods as well.
Posted in jQuery with 5 comments
Was looking for this, thanks for pointing.
By Nicolae Namolovan on Sunday, November 18, 2007 at 10:07 AM
THANK YOU Brandon !!!!!
By Cherry on Sunday, February 3, 2008 at 03:11 PM
thank you for the tip, i tried it before with comma separated but didn’t work in IE, now i see!
By Ryan on Tuesday, September 30, 2008 at 05:46 AM
I was trying with bind(“click,mouseover,mouseenter”…) like we do for multiple selectors, I thought it’s already supported by jquery core. After reading your post now I know it’s not :(
Thanks for pointing that out. But I do not like to use unnecessary plugins that much as long as I can go without it.
By ABM on Wednesday, September 30, 2009 at 07:04 AM
@ABM This is now in jQuery core (actually has been for a while). You use the same syntax as described in this post.
By Brandon Aaron on Wednesday, September 30, 2009 at 03:09 PM