Good day! Tell me, please, how to make the script execute block animation when the block reaches the center of the screen, and not when it only becomes visible, as I have now. Thank you for your help!

$(function() { $('.person').css({'margin-left':'50px'}); $(window).on('scroll', function(e) { if ($(window).scrollTop() > $('.person').offset().top - $(window).height()) { $('.person').css({'margin-left':'10px'}); } }); }); 
 .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> 

  • Probably, I do not understand something, but the example that you have laid out works the way you describe in the code. The change of margin-left occurs exactly when the scrolling reaches the top of the picture (4 line of your js). Apparently, if we correct this line a little higher (for example, the height of the picture), we get what we need. - alexoander

2 answers 2

  $(function() { var person = $('.person'); person.css({ 'margin-left': '50px' }); $(window).on('scroll', function(e) { var h = ($(window).height() - person.height()) / 2; if ($(window).scrollTop() + h > $('.person').offset().top) { $('.person').css({ 'margin-left': '10px' }); } }); }); 
 .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> 

  • Thanks for the help! - LADYX

$(window).scrollTop() + $('.person').height() > $('.person').offset().top

 $(function() { $('.person').css({ 'margin-left': '50px' }); $(window).on('scroll', function(e) { if ($(window).scrollTop() + $('.person').height() > $('.person').offset().top) { $('.person').css({ 'margin-left': '10px' }); } }); }); 
 .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://pp.vk.me/c4966/u79190808/a_98aeef27.jpg"> </div> <p></p> 

  • Thanks for the help! - LADYX