Labels

Monday, March 7, 2016

Limit a DIV to Certain Scroll Height with Javascript

This is very popular nowadays. You can see major websites around the internet are having this feature. Why? Important information
will not get left out if the web page is scrolled down a lot. This can improve the navigation experience of the website substantially. So how is it
done? You may need to know how to fix a DIV before you can fully understand this post. Here are some of my earlier posts related to
this subject:

<script>
setTimeout(function() {window.scrollTo(0, 0);},100); // To make sure when the page is reloaded, the scroll is back
to 0
document.getElementById('fixright').style.top = '50%';

</script>

</body>
</html>

In order to position a DIV on the middle of the right hand side, I prepare the DIV to be always 50% of the total height and the -
100px margin (derived from half of the total height of the DIV which is 200px in this case). In this example, I want to fix the right
hand DIV to be exactly 70x from the top of the page. I need to let the Javascript to do the job for me by checking the mouse scroll
offset. The magic 170px limit can be obtained from adding the half of the total height of the DIV with the target height limit.

The
Javascript will detect the scroll offset if it crosses the 170px marking I set. If it is more than the 170px limit, fix the DIV. If
it is less, let it scroll as it should be but maintain the 50% position relative to the viewable height of the website
window.

One thing to pay attention is when the page is reloaded, the scroll has to go back to 0 or the calibration of the
mechanism of these will be off. If this is not desired, one can consider resorting to cookie to track the relative position of the
DIV and scroll offset. This is a head start to such new web feature. More complex feature can still be incorporated into these codes
such as managing a very long (high) DIV. Enjoy!