Tim Marshall Tim Marshall - 1 month ago 5
Javascript Question

jQuery Listen Only When Click Hold

In my console, my following script starts logging not only upon clicking your mouse wheel but also continues after you stop holding the mouse wheel button.

var mPosX,
mPosY;

$(document).on('mousedown', function (e) {
"use strict";
if( e.which === 2 ) {
e.preventDefault();
mPosX = event.pageX;
mPosY = event.pageX;
$(document).mousemove(function(event){
var CmPosX = event.pageX,
CmPosY = event.pageX;
console.log('Original X: ' + mPosX + ', New X: ' + CmPosX + ' | Original Y: ' + mPosY + ', New Y: ' + CmPosY);
});
}
});


How can I get my script to only log whilst the mouse wheel is held down and stop when you release?

Answer

You'd store something in mousedown and mouseup that you can access in mousemove

$(document).on({
  mousedown: function(e) {
    e.preventDefault();

    if (e.which === 2)
      $(window).data('isDown', true).data('mPosX', e.pageX).data('mPosY', e.pageY);
  },
  mouseup: function(e) {
    e.preventDefault();

    if (e.which === 2) 
      $(window).data('isDown', false);
  },
  mousemove: function(e) {
    if ($(window).data('isDown')) {
      var CmPosX = e.pageX,
          CmPosY = e.pageY,
          mPosX  = $(window).data('mPosX'),
          mPosY  = $(window).data('mPosY');

      console.log('Original X: '    + mPosX +
                  ', New X: '       + CmPosX +
                  ' | Original Y: ' + mPosY +
                  ', New Y: '       + CmPosY);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hold down mousewheel and move ...</p>

Comments