17
votes

I have the following code snippets

$(document).mousedown(function(event) {
    doSomething();
}

I can capture the mousedown event successfully.

I am trying to do the following:

  1. Capture the first mousedown event
  2. I want to detect if the user is still holding the mouse down so I can do something else.
7

7 Answers

26
votes

Something like

var mouseStillDown = false;

$(document).mousedown(function(event) {
    mouseStillDown = true;
    doSomething();
});

function doSomething() {
    if (!mouseStillDown) { return; } // we could have come back from
                                     // SetInterval and the mouse is no longer down
    // do something

    if (mouseStillDown) { setInterval("doSomething", 100); }
}

$(document).mouseup(function(event) {
    mouseStillDown = false;
});
22
votes
var int00; // declared here to make it visible to clearInterval.

$('#trigger').mousedown(function(){
    int00 = setInterval(function() { repeatingfunction(); }, 50);
}).mouseup(function() {
    clearInterval(int00);
});

function repeatingfunction() {
    // This will repeat //
}

You can also put a clearInterval on the mouseleave event.

5
votes

You'd implement some recursion!

var mouseisdown = false;

$(document).mousedown(function(event) {
    mouseisdown = true;
    doSomething();
}).mouseup(function(event) {
    mouseisdown = false;
});

function doSomething(){
    //Code goes here
    if (mouseisdown)
        doSomething();
}
1
votes

You would need to do something like on mouseDown, start doing something and continue doing it till mouseUp event is fired.

1
votes

use the mousedown event to set a flag, and mouseup to unset the flag. Then you can simply check the flag, to see if it is set.

exmaple

var mouseDownFlag = false;
$(document).mousedown(function(event) {
     mouseDownFlag = true;
     someFunc();
}
$(document).mouseup(function(event) {
     mouseUpFlag = true;
}
var someFunc = function(){
     if(mouseDownFLag){//only run this function when the mouse is clicked
     // your code
         setTimeout("somefunc()", 1000); //run this function once per second if your mouse is down.
     }
}

Hope that helps!

1
votes
$(document).ready(function(){

  var mouseStillDown = false;

  $('#some_element').mousedown(function() {
    do_something();
  }).mouseup(function() {
    clearInterval(mouseStillDown);
    mouseStillDown = false;
  });

  function do_something() {

    // add some code here that repeats while mouse down

    if (!mouseStillDown) {
      mouseStillDown = setInterval(do_something, 100);
    }

  }

});
0
votes
let target = document.querySelector(".targetElement");
target.addEventListener('mousedown', event => {
    target.addEventListener('mousemove',doStuff);
});
target.addEventListener('mouseup', event => {
    target.removeEventListener('mousemove',doStuff);
});
function doStuff(event){
    // code
}

I found this much more convenient.