What is the best way to determine if an element is out of the viewport during scrolling?

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
    variable outside the event function scope
    for toggling on a specific interval

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!

Answer №1

extracted from Using jQuery to determine if an element is visible on the screen

HTML Snippet

<div class="box"></div>
<div class="box"></div>
... 
<div class="box orange"></div>
...

JQuery Code Segment

$.fn.isOnScreen = function() {
  var win = $(window);

  var viewport = {
    top: win.scrollTop(),
    left: win.scrollLeft()
  };
  ...
};

$(window).scroll(function() {
  if ($('.orange').isOnScreen() === true) {
    console.log("Element is in viewport")
  }
});

JS Fiddle Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery Validation for implementing a step-by-step validation process in a wizard form

Looking for a way to implement the jQuery Validation Plugin in conjunction with jQuery UI Tabs? How can I use the jQuery Validation Plugin to validate each step triggered by the next button when using tabs? Most examples of the jQuery Validation Plugin foc ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

Executing blur event in AngularJS

Is there a way to set up an input so that when the length is equal to 5, it triggers a blur event automatically? Any tips on how to achieve this? Here is a basic concept of what I'm looking for: <input type="tel" placeholder="type here." ...

The concept of transparency and visual representation

Is there a way to prevent the opacity of the parent div from affecting the opacity of the img? <div class="parent_div" style="opacity:0.2"> <p>Some text</p> <img class="gif" style="opacity: 1;" src="ht ...

Create a dynamic animation of a line being drawn in Three.js

I am trying to create an animation of a Lorenz attractor using Three.js. I found a helpful YouTube tutorial that serves as a guide for this project. You can view a snippet of my current progress here: // SETTING UP THE SCENE // ------------------------ ...

What is the best method for creating a 10-page PHP form that contains more than 100 input fields in an efficient manner?

I am currently in the process of constructing a substantial PHP form that will extend over 10 pages and contain well over 100 input fields. Each input will be stored in a database. I am starting to encounter challenges keeping track of all the variables as ...

utilize bootstrap to align text at the end of columns within a row

How can I use Bootstrap 5 to arrange a div and a canvas in a row until the md breakpoint? I want the canvas to align immediately after the text ends, currently each part has equal width. Is there a way to remove the unused space from the div? https://i. ...

Is it possible to tailor a jQuery widget by providing parameters and substituting my own callback function?

Being a beginner in jquery, I recently customized the jquery combobox to fit my requirements. Now, I want to use this modified component in various sections of my website by passing arguments and a callback function to manage specific events in jquery. How ...

Spacing for Bootstrap Navbar List Items

I've searched through the CSS and I'm unable to identify what is causing the width between the top level links on my navbar. I need them to be slightly smaller so that when it adjusts for a screen below 900px, it doesn't convert into a 2-row ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

Encountering a 404 error when trying to navigate to the next route using the Link component

Having issues with my login route. I've added a Link to the login route inside a button tag in my Navbar component, but when I try to access the route, I'm getting a 404 error page. --app ----pages ------component --------Navbar.js ----- ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

align text vertically over an image

I've come across this question many times, but none of the answers seem to solve my issue. My challenge is centered around aligning text on an image with regards to vertical positioning. Below is the code I'm working with: <div class="col-sm- ...

Choose a file in React by specifying its path instead of manually picking a file

Is there a way for me to automatically select a file from a specified path into my state variable without having to open a select file dialog? I'm looking for a solution where I can bypass the manual selection process. Any suggestions on how this can ...

updating the datepicker input maxDate property to the current date

I am facing a challenge with setting the input date using datepicker. I want to require the user to choose a date less than the current date. Below is the code snippet: <div class="tab-pane fade active in" id="evenement"> < ...

Retrieve a list of files without refreshing the page by using Ajax, Jquery, and PHP when clicked

First and foremost, I want to apologize if this topic has already been covered elsewhere. I am seeking a straightforward solution. I currently have a PHP script that utilizes the glob function to retrieve a list of files from a specific directory. The dire ...

Every attempt to make an Ajax request ends in failure

I'm struggling with my jQuery script, as the AJAX call always fails and I can't figure out why. Here is the function: <script> function submitLoanApplication() { var time = document.getElementById(&apo ...

Ways to update or define a cookie's value using angularJS

The name of the cookie is "NG_TRANSLATE_LANG_KEY" I have a question: How can I modify the value of this cookie from "ru" to another value, such as "fr" or "kk" using AngularJS? ...