julius_aghahowa julius_aghahowa - 6 months ago 16
Javascript Question

Fade in another logo on scroll

I'm currently swapping a logo for smaller logo when the user scrolls down the page. At the moment it's a straight swap. However I'd like to add a nice animated fade in/out so the larger logo fades out, smaller logo fades in and vice-versa.

Here's a pen of my current attempt: http://codepen.io/abbasinho/pen/yyomrB

I've tried to adding

fadeIn
but with not joy.

JS:

$(function() {
var logo = $(".lrg-logo");
$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 500) {
logo.removeClass('lrg-logo').addClass("sml-logo").fadeIn( "slow");
} else {
logo.removeClass("sml-logo").addClass('lrg-logo').fadeIn( "slow");
}

});
});


CSS:

.wrapper {
height: 2000px;
position: relative;
background: green;
}

header {
position: fixed;
width: 100%;
height: 50px;
background: grey;
}

.lrg-logo {
width: 300px;
height: 50px;
text-align: center;
background: red;
}

.sml-logo {
width: 200px;
height: 20px;
text-align: center;
background: red;
}

Answer

2 things:

  • logo must first be hidden in order to fade it in.
  • fade should not happen on every scroll event, but just once when scrolltop > 500

    $(function() {
        var logo = $(".lrg-logo");
        $(window).scroll(function() {    
            var scroll = $(window).scrollTop();
    
        if (scroll >= 500) {
          if(!logo.hasClass("sml-logo")) {
            logo.hide();
            logo.removeClass('lrg-logo').addClass("sml-logo").fadeIn( "slow");
          }
        } else {
          if(!logo.hasClass("lrg-logo")) {
            logo.hide();
            logo.removeClass("sml-logo").addClass('lrg-logo').fadeIn( "slow");
          }
        }
    
      });
    });