Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery mousemove how to stop

I have this fiddle http://jsfiddle.net/JqBZb/193/ where I want my object to move only when the red square is pressed, but I cannot remove the mousemove action when the user releases the mouse. It still moves after that.

HTML:

<div class="pointer">
    <div class="marker"></div>
</div>

CSS:

.marker {
    background:#ED1C24;
    height:2px;
    right:0;
    position:absolute;
    top:35px;
    width:7px
}
.pointer {
    height:72px;
    position:absolute;
    top:82px;
    width:72px;
    border:1px solid red;
 left:100px;
}

JAVASCRIPT:

var img = $('.pointer');

var offset = img.offset();

function mouse(evt) {
    var center_x = (offset.left) + (img.width() / 2);
    var center_y = (offset.top) + (img.height() / 2);
    var mouse_x = evt.pageX;
    var mouse_y = evt.pageY;
    var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
    var degree = (radians * (180 / Math.PI) * -1) + 90;
    img.css('-moz-transform', 'rotate(' + degree + 'deg)');
    img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
    img.css('-o-transform', 'rotate(' + degree + 'deg)');
    img.css('-ms-transform', 'rotate(' + degree + 'deg)');
}

img.mousedown(function (e) {
    $(document).mousemove(mouse);
}).mouseup(function (e) {
    e.stopPropagation();
})

The original rotation script was provided by this answer https://stackoverflow.com/a/10235298/1168944

like image 920
Mike Avatar asked Sep 03 '13 10:09

Mike


People also ask

What is Mousemove event in jQuery?

The mousemove event occurs whenever the mouse pointer moves within the selected element. The mousemove() method triggers the mousemove event, or attaches a function to run when a mousemove event occurs. Note: Each time a user moves the mouse one pixel, a mousemove event occurs.

How to hover jQuery?

jQuery hover() MethodThe hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.


2 Answers

Add this to your script...

$(document).mouseup(function() {
    $(document).off("mousemove", mouse);
});

It unbinds the mousemove event handler whenever you release the mouse button.

http://jsfiddle.net/JqBZb/201/

I updated it to a later version of jQuery as well, in order to accommodate off().

like image 113
Reinstate Monica Cellio Avatar answered Nov 15 '22 12:11

Reinstate Monica Cellio


Create a bool to check if mouseDown is true/false

 var mouseDown = false;
 if(mouseDown ==true){
   //move code
 }

DEMO

like image 41
Anton Avatar answered Nov 15 '22 13:11

Anton