JQuery mouse stop event

I am trying to make a very simple application in which the user can draw into a table with the selected color when the mouse button is clicked, and the event stops when the mouse rises.

The drawing works well, the only problem is that the event does not stop when the mouse is released. I tried this in many ways, but obviously I'm doing something wrong. Also tried to tie and untie the event, but also did not work.

Here you can see one version of the code: http://jsfiddle.net/mFzkG/8/

Any help is much appreciated!

+4
source share
3 answers

All you have to do is bind and cancel the event from the table cell.

var currentColor; $('.colors').click(function() { $(this).fadeTo("fast", 0.40); currentColor = $(this).css("background-color"); $('.colors').not(this).fadeTo("fast", 1); }); $('table').mousedown( function() { $('td').bind('hover', function(){ $(this).css( "background-color", currentColor ); }); }).mouseup(function(){ $('table td').unbind('hover'); $('table').css(function(){ return false; }); }); $("#reset").click(function() { $("td").css("background-color", "white") } ); 

And here jsFiddle works http://jsfiddle.net/mFzkG/12/

+4
source

Why not do it like this:

  var currentColor; var isMouseDown = false; $('.colors').click(function() { $(this).fadeTo("fast", 0.40); currentColor = $(this).css("background-color"); $('.colors').not(this).fadeTo("fast", 1); }); $('td').mousedown(function() { isMouseDown = true; }); $('td').mouseup(function() { isMouseDown = false; }); $('td').hover(function() { if (isMouseDown) { $(this).css("background-color", currentColor); } }); $("#reset").click(function() { $("td").css("background-color", "white") }); 

So, I think the correct implementation would be to capture the mouseup / mousedown events, hold the state in the isMouseDown variable isMouseDown and check this variable in the hover() function.

+2
source

You can also try this jquery code:

 $('table').mousedown( function() { $('td').bind('mousedown mousemove', function(){ $(this).css( "background-color", currentColor ); }); }); $('table').mouseup( function() { $('td').unbind('mousedown mousemove'); }); 
+2
source

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


All Articles