Frank Lucas Frank Lucas - 7 months ago 17
HTML Question

jquery/css transition when reached top of screen

I detect via my jQuery when you are at the top of the page. When you reach the top of the page I show a larger logo. When you're not at the top of the screen the logo is a bit smaller. It works great but I want to make it smooth with a little transition. But it doesn't seem to work.

Here's my jQuery:

jQuery(window).scroll(function () {
if (jQuery(window).scrollTop() >= 1) {
jQuery('.navbar-brand>div').addClass('small-logo');
} else {
jQuery('.navbar-brand>div').removeClass('small-logo');
}
});


And here are my css classes:

.logo{
margin-top: 10px;
width: 250px;
height: 125px;
-webkit-transition: width 1s; /* Safari */
-webkit-transition: height 1s; /* Safari */
transition: width 1s;
transition: height 1s;
}

.small-logo{
width: 150px;
height: 75px;
-webkit-transition: width 1s; /* Safari */
-webkit-transition: height 1s; /* Safari */
transition: width 1s;
transition: height 1s;
}


Anyone can help my out with this little animation?

Thanks in advance!!

Answer

Setting the transition multiple times in a rules just overwrites the previous ones (moreover if you remove a property in one of the two classes it will not be animated, you have to state the new value so you should include the top-margin in the second rule with 0 value)

.logo{
    margin-top: 10px;
    width: 250px;
    height: 125px;
    -webkit-transition: width 1s, height 1s; /* Safari */
    transition: width 1s, height 1s;
}

.small-logo{
    margin-top:0;
    width: 150px;
    height: 75px;
    -webkit-transition: width 1s, height 1s; /* Safari */
    transition: width 1s, height 1s;
}

It would be even cleaner though to keep the initial class and just toggle a new one for the change (with only the properties that change between the two states)

jQuery(window).scroll(function () {
    jQuery('.navbar-brand > .logo').toggleClass('small', jQuery(window).scrollTop() >= 1);
});

and

.logo{
    margin-top: 10px;
    width: 250px;
    height: 125px;
    -webkit-transition: width 1s, height 1s; /* Safari */
    transition: width 1s, height 1s;
}

.logo.small{
    margin-top:0;
    width: 150px;
    height: 75px;
}