Felix Felix - 1 month ago 15
Javascript Question

Mouse Press event in jqery

Hi i need to detect 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 click event , it is combined mouse press and move event .

But i don't understand how to implement it .
Currently i rotate the div using the following code .But this code is based on 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 user can easily adjust the rotation by pressing that button and rotate to any direction and release the mouse
press.When the user release the mouse press then rotation need to set on that particular mouse press release point .

Thank you .

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.