lundi 26 avril 2021

Stop logo image from flickering as user scrolls

I have two different logos and I want to smoothly fade them in and out, switching between them depending on the scrollbar's position. With the code I'm currently using, it switches between the images and applies the fading effect, but it keeps doing it as the user keeps scrolling, giving a flicker effect as a result. Currently, I have the following code:

$(window).on('scroll', function(){

     var headerHeight = $('header').outerHeight(true) / 3;    
     var scrollTop = $(this).scrollTop();
 
     if(scrollTop < headerHeight){

          $('.logo').fadeOut(200, function(){

               $('.logo').attr('src','IMG_URL01').fadeIn(200);

          });   

     }else if (scrollTop > headerHeight){

          $('.logo').fadeOut(200, function(){
              $('.logo').attr('src','IMG_URL02').fadeIn(200);
         
          });
};

Based on the code's structure, I can see why it's giving that flicker effect; The if statement is being applied each time the user scrolls, depending on the scrollbar's position. However, I just don't know what to write and where to write it to apply the if statement only once.

Aucun commentaire:

Enregistrer un commentaire