Skip to content Skip to sidebar Skip to footer

Differentiating Between Mouseup Mousedown And Click

I know that mousedown happens when a user depresses the mouse button, mouseup happens when the release the mouse and click is of course two events mousedown and mouseup. I have thr

Solution 1:

I've rewritten your code utilizing jQuery...

var isDown = false;
var timer;

$('.class').mousedown(function(){
    isDown = false;
    timer = setTimeout(function(){
        isDown = true;
        //createActive();
            console.log('MOUSE DOWN');
    }, 500);
}).mouseup(function(){
    if(isDown === false){
        //openModule();
            console.log('CLICK');
    }else{
            console.log('MOUSE UP');
    }
    clearTimeout(timer);    
});

If you simply add jQuery to your page, my code will automatically attach itself to any element in your document with a class of 'class'.

I've commented out your createActive(); and openModule(); calls so that you can play around with it (viewing your javascript console at runtime will show you the script in action - remove the console.log() stuff when you're done playing). This code could be optimised a bit more but it will give you the general idea.

Your timer variable needed to be created globally (I moved it out of the function).

In this case (declaring a mousedown time barrier) the click function will be rendered useless so I've improvised it into the mouseup function.

It's good to know core javascript, but jQuery is just too easy and powerful to ignore.


Solution 2:

Try this:

const isDown = ref(false)
const timer = ref(0)

const mouseDown = () => {
  isDown.value = true
  timer.value = setTimeout(() => {
    isDown.value = false
  }, 120)
}

const mouseUp = () => {
  if (isDown.value === true) {
    hideModal()
  } else {
    return
  }
  clearTimeout(timer.value)
}

Post a Comment for "Differentiating Between Mouseup Mousedown And Click"