Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hold event with javascript

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...
}
like image 357
avantimaestro Avatar asked Mar 18 '23 16:03

avantimaestro


2 Answers

(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>
like image 78
epascarello Avatar answered Mar 28 '23 21:03

epascarello


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');
}
like image 40
cport1 Avatar answered Mar 28 '23 20:03

cport1