JQuery: shortcuts for the most used events
This is another quick post on events. In the previous posts, we’ve met the bind and unbind method which is used for subscribing and unsubscribing HTML element’s events. So, if you’re interested in subscribing one of the most common events, then you’ll be pleased to know that JQuery introduces several “shortcut” methods. The interesting thing about these methods is that they work in “two modes”: when you pass a function, you’re effectively setting up an event handler; on the other hand, when you call the function without the parameter, you end up executing the previous handlers that have been hooked up.
Here’s a small snippet that shows how to handle the click event:
$("#bt").click(function() { alert("hi"); });
$("#bt").click();
As I’ve said, the first line sets up an event handler. In fact, it produces exactly the same result as the bind method (but with less key presses:)). Whenever someone clicks over the #bt element, the anonymous method we’ve passed to the click method will be fired.
The second line ends up executing all the methods that have been set up as an event handler. Notice that there’s no unclick method so if you need to cancel an existing subscription, you’ll still need to use the unbind method. And that’s all for today. Keep tuned for more on JQuery.