One of my tasks is to detect whether an element is within the viewport as the user scrolls. If the element is outside the viewport, I apply a class that affixes the element to the top.
The function I employ to determine if the element is outside the viewport goes like this:
isElementInViewport : function(el) {
// A special feature for those utilizing jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
I have set up a scroll event which triggers this function :
$(window).on('scroll', function(event){
testObject.isElementInViewport(event.target);
}
However, while scrolling, my Lenovo Yoga's CPU usage skyrockets. I've experimented with:
polling
using an interval- applying a
timeout function
and a
for toggling on a specific intervalvariable outside the event function scope
These methods do work, but I'm in need of a solution that minimizes performance impacts, especially since the page already has a significant amount of JavaScript running. Additionally, I require the element to be fixed to the top immediately upon exiting the viewport, without any delay.
Is there a low-performance alternative for this task? Can it possibly be achieved solely through CSS?
Edit
Upon reflection, I realize that I didn't phrase my query correctly. The existing answers do function, but they still incur substantial CPU strain when I perform slight up-and-down scrolls:
https://i.sstatic.net/xbAKB.jpg https://i.sstatic.net/gmJUM.jpg
I urgently need to reduce the script's CPU demands!