Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

google chrome - How do I listen for triple clicks in JavaScript?

If this is for a double-click:

window.addEventListener("dblclick", function(event) { }, false);

How can I capture a triple-click? This is for a pinned tab in Google Chrome.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to write your own triple-click implementation because no native event exists to capture 3 clicks in a row. Fortunately, modern browsers have event.detail, which the MDN documentation describes as:

A count of consecutive clicks that happened in a short amount of time, incremented by one.

This means you can simply check the value of this property and see if it is 3:

window.addEventListener('click', function (evt) {
    if (evt.detail === 3) {
        alert('triple click!');
    }
});

Working demo: http://jsfiddle.net/L6d0p4jo/


If you need support for IE 8, the best approach is to capture a double-click, followed by a triple-click — something like this, for example:

var timer,          // timer required to reset
    timeout = 200;  // timer reset in ms

window.addEventListener("dblclick", function (evt) {
    timer = setTimeout(function () {
        timer = null;
    }, timeout);
});
window.addEventListener("click", function (evt) {
    if (timer) {
        clearTimeout(timer);
        timer = null;
        executeTripleClickFunction();
    }
});

Working demo: http://jsfiddle.net/YDFLV/

The reason for this is that old IE browsers will not fire two consecutive click events for a double click. Don't forget to use attachEvent in place of addEventListener for IE 8.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...