Disable mousemove on click

I am experimenting with dragging and dropping "n", this is my code here:

$('.box-title').live('mousedown click', function(e) { var self = $(this); var Box = self.parent('#box'); if(e.type == 'mousedown') { $(window).mousemove(function(e) { Box.css({ cursor: 'move', top: e.pageY - 15, left: e.pageX - 125 }); }); } else if(e.type == 'click') { Box.css({ cursor: 'default', top: e.pageY - 15, left: e.pageX - 125 }); } }); 

In mousedown, it must initiate the drag effect by moving the mouse, after that if I want to dock / lower the box where I want it, I click on it, it must disable the move, but if I click on it, it does not stop moving - just watching my mouse. How can you stop the drag?

+4
source share
3 answers

You need to untie the mousemove handler that is still currently attached, for example:

 function setPos(e) { //can be $('#box') in this case... $(this).parent('#box').css({ cursor: 'move', top: e.pageY - 15, left: e.pageX - 125 }); } $('.box-title').live('mousedown click', function(e) { if(e.type == 'mousedown') { $(window).mousemove(setPos); } else if(e.type == 'click') { $(window).unbind('mousemove', setPos); } }); 

Or, in jQuery 1.4.3+, the .live() handler might be a little cleaner:

 $('.box-title').live({ mousedown: function() { $(window).mousemove(setPos); }, click: function() { $(window).unbind('mousemove', setPos); } }); 

Aside, it seems you have a few id="box" elements on the page ... make sure you use the classes in these cases, in this code $(this).parent('#box') will be $(this).closest('.box') .

+8
source

Try to add

$(window).unbind('mousemove')

in the click event.

+3
source
 else if(e.type == 'click') { $(window).unbind('mousemove') } 

But in fact, you should name the event so that you only untie the corresponding event listener.

Binding: $(window).bind('mousemove.dragging', function(){});

Undo: $(window).unbind('mousemove.dragging', function(){});

+1
source

Source: https://habr.com/ru/post/1334113/


All Articles