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
Well for one thing you don’t have to continually re-generate the jQuery object around the “.button” selector:
Doesn’t make it much shorter. You could also consider doing this with
live()ordelegate()instead of dealing with the buttons directly. That’s probably what I’d do, since your selector here is cheap to check when an event happens. If you have a lot of buttons (which would probably a bad idea anyway, especially if they’re all pulsating and throbbing as you move the mouse around) it can be a little slow to assign all the handlers.
edit — fixed thanks to @MvanGeest