Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event to stop on mouseup

I am trying to make a very simple application where the user can draw into a table with a selected color when the mouse button is down, and the event stops when the mouse is up.

The drawing works well, the only problem is that the event doesn't stop when the mouse is released. I've tried it in many ways, but obviously I am doing something wrong. Also tried to bind and unbind the event, but didn't work either.

You can see one version of the code here: http://jsfiddle.net/mFzkG/8/

Any help much appreciated!

like image 876
Zoltan Avatar asked May 29 '12 15:05

Zoltan


2 Answers

All you have to do is bind and unbind event from 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 is working jsFiddle http://jsfiddle.net/mFzkG/12/

like image 175
Senad Meškin Avatar answered Oct 01 '22 15:10

Senad Meškin


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 a variable isMouseDown and check this variable in the hover() function.

like image 36
Moritz Petersen Avatar answered Oct 01 '22 13:10

Moritz Petersen