Artem Svirskyi
Artem Svirskyi

Reputation: 7849

Custom events in JavaScript

Is it possible to create custom events (for example, triple click or swipe) in JavaScript that will trigger with certain conditions? Perhaps to listen to this custom event:

addEventListener('trplclick', handler, false); 

So handler will be called only if 3 clicks were done within 600 ms, for example.

Upvotes: 2

Views: 320

Answers (2)

Rex
Rex

Reputation: 454

See similar question here: How do I listen for triple clicks in JavaScript?

Basically what it does is combining double click event and single click event together to mimic triple click. When double click event triggers, set a timeout for 200ms. If there's a following click coming up, check if the timer timed out. If this click happens 200ms later after the previous double click(at this time, timer was set to null in double click handler), discard this click, otherwise count it as a triple click.

For setting custom event in general, I will refer you to Nicholas C. Zakas's blog post: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

Upvotes: 0

Matt Zeunert
Matt Zeunert

Reputation: 16571

You need to trigger the triplclick event yourself. Listen to the individual click events, count them, and trigger triplclick when it makes sense.

Have a look at document.dispatchEvent.

I'm using jQuery to demonstrate the concept, but you don't need to:

var count = 0;
var resetTimeout - 1;
$(element).on("click", function(){
    count++;
    clearTimeout(resetTimeout);
    if (count === 3)
    {
        count = 0;
        $(element).trigger("trplclick");
    }
    else 
    {
        resetTimeout = setTimeout(function(){
            count = 0; // Don't count if no click within the last second.
        }, 1000);
    }
});

Upvotes: 1

Related Questions