I am trying to check if an element is inside my viewport when scrolling. If it is outside my viewport, I add a class that fixes the element to the top.
The function I use to determine if the element is outside the viewport is:
isElementInViewport : function(el) {
//special bonus for those using 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 added a scroll event which fires this function :
$(window).on('scroll', function(event){
testObject.isElementInViewport(event.target);
}
The problem here is that while scrolling, my Lenovo Yoga's CPU goes crazy. I have tried:
polling
with an interval- using a
timeout function
and avariable outside the event function scope
to toggle on a certain interval
Both methods work, but I need a way to minimize performance impacts, because the page I use this in already has LOADS of JS working. I also need to fix the bar to top as soon as it gets outside the viewport and not a few milliseconds later.
Are there any low-performance solutions for this? Can this be done in CSS only?
Edit
I've noticed that I didn't asked my question right. The current answers below are working, but give the same HUGE performance impact when I scroll up and down a bit:
I need to prevent the script from needing so much CPU power!