Hold event with javascript

17,189

Solution 1

(function() {

  var mouseTimer;
  function mouseDown() { 
      mouseUp();
      mouseTimer = window.setTimeout(execMouseDown,2000); //set timeout to fire in 2 seconds when the user presses mouse button down
  }

  function mouseUp() { 
      if (mouseTimer) window.clearTimeout(mouseTimer);  //cancel timer when mouse button is released
      div.style.backgroundColor = "#FFFFFF";
  }

  function execMouseDown() { 
      div.style.backgroundColor = "#CFCF00";
  }

  var div = document.getElementById("bam");
  div.addEventListener("mousedown", mouseDown);
  document.body.addEventListener("mouseup", mouseUp);  //listen for mouse up event on body, not just the element you originally clicked on
  
}());
#bam { width:100px; height: 100px; border: 1px solid black; }
<div id="bam"> Hold mouse button for 2 seconds. </div>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>
<p>Bacon</p>

Solution 2

I would do something like this to get the difference between mousedown and mouseup. Then, I would do an if/else statement with that diff variable that I created.

Here's a fiddle:: http://jsfiddle.net/mgfkdu9x/2/

<button id="element">My Button</button>

(function () {
    var element = document.getElementById('element'),
        start, 
        end;

    element.onmousedown = function () {
      setTimeout(function() { 
          if (element.onmousedown=true)
              toBeExecutedNMillisecondsAfterAnchorWasClicked();
      }, 5000);
    };

})();

function toBeExecutedNMillisecondsAfterAnchorWasClicked() {
     console.log('function start');
}
Share:
17,189
Admin
Author by

Admin

Updated on June 21, 2022

Comments

  • Admin
    Admin almost 2 years

    I really would like to know if there is any way to execute a function when you tap (on mobile device) or click (on desktop device) a form submit/anchor/etc. and hold it for some amount of time WITHOUT using jQuery!

    function clicked() {
        //set some kind of timer or so...
    }
    
    function toBeExecutedNMillisecondsAfterAnchorWasClicked() {
         //do some stuff...
    }