views:

27

answers:

2

Hey everyone, I have achieved the effect described in the title using the following code:

$(document).ready(function(){

$('.button').mousedown(function() {
    $(this).animate({ 'top': '3px' }, 70);
});
$('.button').mouseup(function() {
    $(this).animate({ 'top': '0px' }, 70);
});
$('.button').hover(function() {
    $(this).stop().animate({ 
        color: '#fff',
        backgroundColor: '#000' 
    }, 250);
});
$('.button').mouseout(function() {
    $(this).stop().animate({ 
        color: '#000',
        backgroundColor: '#fff' 
    }, 250);
});

});

I am pretty sure that that this code can be reduced significantly, can anyone help me out? Please note that I want the button to animate when the mouse is clicked and not return to it's original position until the mouse is released.

Cheers

A: 

You're abusing .hover(). From the API reference:

Description: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

So this will speed things up:

$('.button').hover(function() {
    $(this).stop().animate({ 
        color: '#fff',
        backgroundColor: '#000' 
    }, 250);
}, function() {
    $(this).stop().animate({ 
        color: '#000',
        backgroundColor: '#fff' 
    }, 250);
});

But I believe the code cannot really be optimized further. You could use .bind() and a hash, but that's only marginally faster/better.

MvanGeest
A: 
Pointy
Please do consider that the `hover` is executing twice, which includes one useless occasion.
MvanGeest
I fixed the hover I think - I changed it to take 2 functions by stealing his old "mouseout" code. Is that right?
Pointy
It's the same as I did, and right according to the docs. Of course, only he can tell us if it works.
MvanGeest
Thanks, you were both really helpful. I forgot that I could chain the methods instead of referencing the selector each time. Removing the second (unnecessary) hover is great. Although it's not much shorter its definitely an improvement.
DaveKingsnorth