简体   繁体   中英

Animate on scroll not working on mobile as on desktop scroll.Top() jQuery

It's my first time that i'm creating animations on scroll. I'm using documentsize variable and scrollTop() after reaching to the element i change the class of that element to do effect. It's working perfectly on desktop but on mobile only first element works and others not may be scrollTop() calculate differently on desktop and mobile so i need to use condition for applying different code for desktop and mobile. I'm not sure that's why i'm asking here if there is only this way.

Thanks.

 var documentsize = $(document),
  firstelement = $('.firstelement'),
  firstelementtime = 200,
  secondelement = $('.secondelement'),
  secondelementtime = 1400;


  documentsize.on('scroll',function(){

     if(documentsize.scrollTop() > firstelementtime){

         $('.firstelement').removeClass('myanimation');
         $('.firstelement').addClass('fadeInLeft');
     }


     if(documentsize.scrollTop() > secondelementtime){

         $('.secondelement').removeClass('myanimation');
         $('.secondelement').addClass('fadeInRight');
     }












     if(documentsize.scrollTop() < firstelementtime){

         $('.firstelement').removeClass('fadeInLeft');

           setTimeout(function(){

             $('.firstelement').addClass('myanimation');

           },500);
     }         



    if(documentsize.scrollTop() < secondelementtime){

         $('.secondelement').removeClass('fadeInRight');

           setTimeout(function(){

             $('.secondelement').addClass('myanimation');

           },500);
     }  

  });

If you are worried about calculating different values in desktop and pc, its better to use either $(element).offset() to get top and left values according to the parent element or pure javascript element.offsetTop. After that you can use $(parent).scroll() to scroll down by the pixel value you get from the offset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM