I wrote a script that does not allow the floating button to go above the area where the script is used, while scrolling down, the button climbs to the very bottom of the site. How to make it stop at the end of the block where my script is used?

<script type="text/javascript"> $(function() { var offset = $(".spoiler-hd").offset(); var topPadding = 45; $(window).scroll(function() { if ($(window).scrollTop() > offset.top) { $(".spoiler-hd").stop().animate({marginTop: $(window).scrollTop() - offset.top + topPadding}); } else {$(".spoiler-hd").stop().animate({marginTop: 300});};}); }); </script> 

    1 answer 1

    You start to move an element at the moment when the position of the document scroll is greater than the position of the upper edge of the block you need ( $(window).scrollTop() > offset.top ).

    Nothing prevents you from adding a condition to a non-moving element there when the scrolling has passed the bottom edge of the block you need. That is, for example:

     if($(window).scrollTop() > offset.top && $(window).scrollTop() < (offset.top + offset.offsetHeight) ) 
    • Sorry, I didn’t quite understand how it should look like .. How do I get the script right, does not work yet - user
    • @user, I simply replaced your condition in if . It is likely that I, not seeing your markup, am mistaken. ) - Rolandius
    • @user, did you figure it out? I can write a more detailed answer, if not. - Rolandius
    • did not understand (Please explain - user