Good day! On the page there are a lot of blocks with the class .person. And when scrolling the page, as soon as the first block with this class gets into the visible part of the screen, the script changes the property for all the blocks with the class .person at once. And how can you make the script alternately change the property for each block as soon as it gets into the visible part of the screen?

$(function() { var person = $('.person'); person.css({ 'margin-left': '300px' }); $(window).on('scroll', function(e) { var h = ($(window).height() - person.height()) / 2; if ($(window).scrollTop() + $('.person').height() > $('.person').offset().top) { $('.person').css({ 'margin-left': '10px' }); } else { $('.person').css({ 'margin-left': '300px' }); } }); }); 
 .person { margin-left: 10px; transition: margin-left .4s; } p { height: 700px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> 

    1 answer 1

    For example, apply each :

      $(function() { var person = $('.person'); person.css({ 'margin-left': '300px' }); $(window).on('scroll', function(e) { var h = ($(window).height() - person.height()) / 2; $('.person').each(function(){ if ($(window).scrollTop() + $(this).height() > $(this).offset().top) { $(this).css({ 'margin-left': '10px' }); } else { $(this).css({ 'margin-left': '300px' }); } }); }); }); 
     .person { margin-left: 10px; transition: margin-left .4s; } p { height: 700px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> 

    • Elena, I welcome you! Thank you for your help. Yes, it works. The only thing now is that the animation of the block was played not in the center of the screen (vertically), but at the top of the screen. What could be the error? - LADYX
    • Thank you for your help. Yes, it works. The only thing now is that the animation of the block was played not in the center of the screen (vertically), but at the top of the screen. What could be the error? - LADYX
    • I do not even know. - HamSter
    • and thank you so much! Good luck! - LADYX