Tom Maxwell
Tom Maxwell

Reputation: 9573

jQuery Animate() hover?

I'm using jQuery for the first time, specifically on my own website, and I'm using the animate function to make an email tab move down slightly when hovered upon (check it out in the top right: http://www.tommaxwell.me). However, I don't know how to make the animation pause after completing. I can make the first animation and the animation necessary to have it return to its original state, but I want it to return to its original state after the user moves their cursor away. Here's the code, and keep in mind I realize why it doesn't work, I just don't know a solution as I'm new to jQuery.

$("#emailme").hover(function(){
  $("#emailme").animate({
    paddingTop: "15px"
  }, 100, function() {
    $("#emailme").animate({
        paddingTop: "10px"
    }, 100)
  });
});

Upvotes: 0

Views: 4696

Answers (2)

Asad Saeeduddin
Asad Saeeduddin

Reputation: 46628

The second argument to hover is the callback to invoke when the user moves their mouse away.

$("#emailme").hover(function() {
    $(this).animate({
        paddingTop: "15px"
    }, 100);
}, function() {
    $(this).animate({
        paddingTop: "10px"
    }, 100)
});

So the general idea is:

$('selector').hover(function(){
    //stuff to do on mouse in
}, function(){
    //stuff to do on mouse out
});

Upvotes: 1

Vytautas Butkus
Vytautas Butkus

Reputation: 5535

You should use the functions $element.mouseover(fn) and $element.mouseout(fn).

So it should be like this:

$("#emailme").mouseover(function(){
    $(this).animate({
        paddingTop: "15px"
    }, 100);
}).mouseout(function(){
    $(this).animate({
        paddingTop: "10px"
    }, 100);
});

This means that attach event handlers to two different events: when you move your mouse over the element it expands and when you move your mouse out it subtracts - just as you want it.

Upvotes: 0

Related Questions