Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .removeAttr('style') after .animate() does not work

Tags:

html

jquery

I've got the following nav

<nav>
   <a href="#" class="current">HOME</a>
   <a href="#">ABOUT</a><a href="#">CONTACT</a>
</nav>

with this styling:

nav a {
    font-family: monospace;
    display: inline-block;
    width: 114px;
    height: 29px;
    font-size: 14px;
    line-height: 29px;
    text-align: center;
    text-decoration: none;
    color: white;
    background-color: #004870;
}
nav a {
    margin-left: 7px;
}
nav a.current{
    background-color: #585858;
    color: white;
}

And want to animate the BG color on mouseover to #585858 and back to #a3a3a3 after mouseleave and the style attribute to get removed again.

I tried this code but the style attribute remains after mouseleave:

$(document).ready(function() {
   $('nav a:not(.current)').mouseenter(function() {
   $(this).stop().animate( {
          backgroundColor: '#585858'
   }, 300);
});
$('nav a:not(.current)').mouseleave(function() {
$(this).stop().animate( {
    backgroundColor: '#004870'
}, 300).removeAttr('style');
    });
});

So what changes are needed to remove the style attribute after the animation finished?

like image 288
Johannes Trümpelmann Avatar asked Nov 20 '25 01:11

Johannes Trümpelmann


1 Answers

You are missing here the fact, that jQuery.animate is asynchronous, so your removeAttr is called before the animation finishes. You should use the complete callback to call removeAttr.

You also need the jQuery.Color() plugin for jQuery.animate to be able to animate background-color.

var $this = $(this);
$this.stop().animate({ backgroundColor: jQuery.Color("rgb(0, 72, 112)") }, {
    duration: 300,
    complete: function() { $this.removeAttr('style') }
});
like image 155
tpeczek Avatar answered Nov 21 '25 17:11

tpeczek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!