Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm making a web app where a button's behavior is different if the user clicks vs holds the button. I have been experimenting with different timings and it got me wondering if there is any established standard for this kind of thing.

For clarification: I am wondering if there is an exact timing that is standard. Below is the code I am using with 150ms being the threshold for a hold.

function onMouseDown()
{
    var holdTimeout = setTimeout(function()
    {
        //Hold code (also cancels click event)
    }, 150);

    var cancelHold = function()
    {
        clearTimeout(holdTimeout);
    };
    window.onmouseup = cancelHold;
}

function onClick()
{
    //Click code
}
See Question&Answers more detail:os

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

1 Answer

Answering exactly your question, hold becomes click. You could set the click event (it's release in fact), inside the mousedown event. Run the code below and try holding and release the mouse button.

document.getElementById("click").addEventListener('mousedown', (e) => {
  var i = 0;
  var int = setInterval(() => {
    console.log("hold " + i++);//<-- actions when we hold the button
  }, 200)

  document.getElementById("click").addEventListener("click", () => {

    clearInterval(int);

    console.log("release")//<-- actions when we release the button

  })

});
<div id="click">click</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...