Building a triple click
Written by on April 1st, 2009 in Uncategorized.
Brandon Aaron has a nice article on building a special event for triple clicking on an element using jQuery.
To illustrate the API I’m going to create a new event type called “tripleclick”. To be fired it will require the user click the element three times. If we were to make this a typical jQuery plugin we would create jQuery.fn.tripleclick. However, I want to be able to take advantage of the bind syntax along with the other benefits like event normalization, data, and namespaces that the jQuery event system provides.
The first thing we need to do is create the special event. Each special event has a setup and a teardown method. The setup method gets called when the event is bound and the teardown method gets called when the event is unbound.
It is important to note that these two methods only get called the first time an event of a particular type is bound/unbound per an element. This is because the jQuery event system actually only binds one handler per an event type per an element and manages the other bound handlers itself. In jQuery 1.3 there is a new special event type called “Special All” that operates for all handlers but has a slightly different behavior. However, that is for another article.
it leaves us with:
-
-
jQuery.event.special.tripleclick = {
-
setup: function(data, namespaces) {
-
var elem = this, $elem = jQuery(elem);
-
$elem.bind(‘click’, jQuery.event.special.tripleclick.handler);
-
},
-
-
teardown: function(namespaces) {
-
var elem = this, $elem = jQuery(elem);
-
$elem.unbind(‘click’, jQuery.event.special.tripleclick.handler);
-
},
-
-
handler: function(event) {
-
var elem = this, $elem = jQuery(elem), clicks = $elem.data(‘clicks’) || 0;
-
clicks += 1;
-
if ( clicks === 3 ) {
-
clicks = 0;
-
// set event type to "tripleclick"
-
event.type = “tripleclick”;
-
// let jQuery handle the triggering of "tripleclick" event handlers
-
jQuery.event.handle.apply(this, arguments)
-
}
-
$elem.data(‘clicks’, clicks);
-
}
-
};
-
Source: Ajaxian » Front Page
Original Article: http://feedproxy.google.com/~r/ajaxian/~3/jES5knYlw0M/building-a-triple-click