Felix Felix - 1 month ago 23
Javascript Question

Mouse press event in jQuery

I need to detect the mouse pressed event in jQuery. I see this question and it's answer. It is the exact one I needed, because here the action is happen only if the mouse is pressed and moved. It is not a click event, it is combined mouse press and move event.

I don't understand how to implement it. Currently I rotate the div using the following code, but this code is based on the mousedown event:



var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};

$('.resizeButton').on("mousedown", function(e) {
var startX = e.pageX;
$(document).mousemove(function(e){
rotation = startX - e.pageX;
$('.test').rotate(rotation);
});
});
$('.resizeButton').on("mouseup", function(){
$(document).unbind( "mousemove" );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Hello
<button class="resizeButton"> </button>
</div>





Please help to convert it to mouse press and move event, so that the user can easily adjust the rotation by pressing that button and rotate to any direction and release the mouse press. When the user releases the mouse press and then rotation needs to set on that particular mouse press release point.

Answer

There are some issues in your code.

First of all, the "mouseup" event handler doesn't get fired because your mouse isn't over the checkbox when you release the mouse. You have to bind the event to the document for example.

Then, instead of binding and unbinding event handlers, it's probably easier to store the state of the mouse, and rotate only if the mouse is pressed.

var rotation = 0;
var rotating = false;
var startX = 0;

jQuery.fn.rotate = function(degrees) {
  $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};
                    
$(document).mousemove(function(e){
  if (!rotating) return;
  rotation = startX - e.clientX;
  $('.test').rotate(rotation);      
});

$(document).on("mouseup", function(){
  rotating = false;
});

$('.resizeButton').on("mousedown", function(e) {
  rotating = true;
  startX = e.clientX;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Hello 

<button class="resizeButton"> </button></div>

To have the button follow the mouse pointer during rotation, you would probably need to use some sin and cos functions to determine the angle of rotation, and you'd probably need to adjust the radius too.