17

I know mousedown is when user press the mouse, mouseup is when user release the mouse. But I want to listen the event after user press the mouse and hold it until it release. Any ideas?

Yves M.
  • 29,855
  • 23
  • 108
  • 144
user2268624
  • 248
  • 2
  • 4
  • 8

6 Answers6

15

If you want the hold state then it will be the state when you are in mousedown event state for a while. This state exists when you press mousedown but not mouseup. Hence you need to take a variable which records the current state of the event.

jQuery

$('div').on('mousedown mouseup', function mouseState(e) {
    if (e.type == "mousedown") {
        //code triggers on hold
        console.log("hold");
    }
});

Working Fiddle

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • There's no need for the ternary - `==` always returns a boolean. – Qantas 94 Heavy Sep 03 '13 at 05:25
  • @AkinHwan please elaborate. better to post a new question and share the link if you think I can help you. – Mr_Green Jun 06 '19 at 16:28
  • Hi Mr_Green, specifically I was trying to change my working code that used pointerevents with mouse events api since that seems cross browser supported. https://stackoverflow.com/questions/56463451/workaround-for-safari-ios-pointer-events-not-supported – Akin Hwan Jun 07 '19 at 13:50
  • Is there a way to code this in plain JavaScript? I can't find how to translate `.on('mousedown mouseup'`. –  Aug 21 '20 at 18:05
  • @LukoFoks you have to write separately for both events using `addEventListener` – Mr_Green Aug 22 '20 at 20:06
  • This will trigger on every mouse click, better place a debounce to capture hold state. – varundhariyal Jul 05 '21 at 06:54
5

var setint  = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
   clearInterval(setint);
   val = 0;
   setint = setInterval(function () {
       $("#putdata").val(++val);
        console.log("mousehold");
   },50);
});
$('#hold').on("mouseleave mouseup", function () {
   val = 0;
   $("#putdata").val(val);
   clearInterval(setint);
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html>
shekhar kumar
  • 61
  • 1
  • 5
  • I'm building a web-based d-pad for a servo controller and this is exactly what I needed to see how long the up/down/left/right was being held. – chrisbyte Feb 18 '21 at 02:36
4

Try this

Add respective mouse events to folowing functions

mouse = false;
function mousedown()
{
  mouse = true;
  callEvent();
}
function mouseup()
{
  mouse =false;
}
function callEvent()
{
 if(mouse)
 {
   // do whatever you want
   // it will continue executing until mouse is not released


   setTimeout("callEvent()",1);
 }
 else
 return;
}
Voonic
  • 4,667
  • 3
  • 27
  • 58
  • 2
    This is very dangers (bug potential) solution. If the user release the mouse button outside the window (browser) the `mouseup` event will not fire and your method: callEvent will run in a loop forever. – Gil Epshtain Jan 28 '19 at 13:58
  • @GilEpshtain i have just shown how to tackle asked problem, i think OP knows which event listeners(mouse down, mouse up, mouse out) needs to be added. If all event listeners added properly then there will not be any issue. – Voonic Jan 29 '19 at 07:42
2

From jquery.com :

HTML :

<p>Press mouse and release here.</p>

Script:

$("p").mouseup(function(){
    $(this).append('<span style="color:#F00;">Mouse up.</span>');
}).mousedown(function(){
    $(this).append('<span style="color:#00F;">Mouse down.</span>');
});

Full url : http://api.jquery.com/mousedown/

Roy M J
  • 6,926
  • 7
  • 51
  • 78
1

Use setInterval() to keep executing your code when until the mouse is down and use clearInterval() to stop the setInterval() function when the mouse is released.

var id;
window.onmousedown = () => {
    console.log(“holding..”)//Since setInterval doesn’t start
    //immediately and causes clearInterval to execute first

    id=setInterval(()=>{
        console.log("holding...")
    },300)
}
window.onmouseup = () => {
    clearInterval(id)
    console.log("released...")
}
Sumit
  • 11
  • 3
0

logic to ignore the click and get the hold only, in above mentioned answer by Sumit, a check can be added to ignore the click and listen to only the hold:

var id;
var check = null;
  

window.onmousedown = () => {
      //Since setInterval doesn’t start
      //immediately and causes clearInterval to execute first
    check = null;
      id=setInterval(()=>{
          if(check == null)
          console.log("holding...")
      },300)
  }

  window.onmouseup = () => {
      clearInterval(id)
      id = null;
      check = 1;
      console.log("released...")
  }
badar
  • 81
  • 1
  • 3