Monday, July 23, 2012

jQuery Function Of The Week: one

jQuery's one function is an extremely useful function when you want an event to fire exactly one time.   According to the official jQuery documentation use one to, "Attach a handler to an event for the elements. The handler is executed at most once per element"  One is a much more terse way of setting an event handler and calling unbind() or off() in the handler function.

The easiest use of one is to pass it an event and a handler like so:

Click Here to Demo on JS Bin

You can click the link as many times as you wish, however the event will only fire once.

You can pass in more than one event handler to the one function by passing in a list of events separated by a space.  When you do this each event will fire once.  In this example the event will fire 3 times, one time for each event:

Click Here to Demo on JS Bin

You can also  pass in custom data to the event handler, the data comes attached to the object like so:

Click Here to Demo on JS Bin

One additional thing you can do with the one function is use an additional selector to pass into the one event that will attach the event to exactly one of the descendants of the matched set. In the following example click on any of the li elements, then click on another, you'll see the event only fires for the first element selected.

Click Here to Demo on JS Bin

Check out the all of the jQuery function's of the week.

Fork me on GitHub