Zoltan
Zoltan

Reputation: 163

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!

Upvotes: 6

Views: 5162

Answers (3)

Syed Ahmed
Syed Ahmed

Reputation: 1645

You might 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');
    });

Upvotes: 2

Moritz Petersen
Moritz Petersen

Reputation: 13047

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.

Upvotes: 2

Senad Meškin
Senad Meškin

Reputation: 13756

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/

Upvotes: 6

Related Questions