Javascript - issue with accurately retrieving element offset value while scrolling

My goal is to dynamically change classes for elements based on their position during scrolling. I am trying to calculate the top offset element value and adjust the classes accordingly. Here is the function I am using:

handleScroll () {
    const header = document.querySelector('#header');
    const content = document.querySelector('#content');
    const rect = header.getBoundingClientRect();
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const headerTop = rect.top + scrollTop;
    console.log(headerTop);
    if (window.scrollY > headerTop) {
      header.classList.add('fixed');
      content.classList.add('content-margin');
    } else {
      header.classList.remove('fixed');
      content.classList.remove('content-margin');
    }
  }
},
beforeMount () {
  window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy () {
  window.removeEventListener('scroll', this.handleScroll);
}

However, I noticed that the console.log(headerTop); value changes continuously while scrolling instead of showing the correct value immediately. How can I ensure that I get the accurate value during scroll?

Answer №1

Utilizing the getBoundingClientRect() method allows you to obtain a box that is relative to the position of the current window. In cases where the element is in a sticky state, its top value will typically be anchored at 0 or another constant value.

One potential solution to this issue involves inserting an empty div preceding the sticky element and utilizing it as a point of reference for offsets.

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

Preserve the XHR-generated configuration when the browser is refreshed

My PHP page features a navigation menu with options such as Home, About Us, and Profile. When clicking on the "About Us" link from the home page, it loads an Ajax response displaying the information without reloading the page. However, if the user decide ...

Creating modules or classes in ExpressJS

I am in the process of defining a modules/class that will contain a list of methods. Each method will have an instance of a service such as loggers, promises, etc. What is the best way to ensure clean code while implementing this? Currently, my code incl ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

Benefits of utilizing minified AngularJS versions (Exploring the advantages of angular.min.js over angular.js, along with the inclusion of angular.min.js.map)

After introducing angular.min.js into my project, I encountered a problem. http://localhost:8000/AngularProject/angular.min.js.map 404 (Not Found) angular.min.js.map:1 Upon further investigation, I discovered that including angular.min.js.map resolve ...

What is the best way to remove words from an object's value that begin with a specific keyword using JavaScript?

Here is a sample array. I need to remove the words row-? from the className property. [ { type: "text", name: "text-1632646960432-0", satir: "1", className: "form-control col-lg-3 row-1" }, { ...

How can you access the index of an object in Vue.js when one of its properties has been modified

Here's the Vue component code I'm working with: data: function () { return { products: [ { product_id: '', price: ''}, { product_id: '', price: ''}, ], ...

Converting Byte strings to Byte arrays in Node.js using JavaScript

Currently facing a challenge while trying to complete the pythonchallenge using JS and Node. Stuck on challenge 8 where I need to decompress a string using bzip2: BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x ...

Retrieve content from inner tag using Selenium

Check out this snippet of HTML code: <label class="abc"> <span class="bcd">Text1</span> Text2 </label> Is there a more efficient method to extract only Text2 using a selenium script? I currently extract Text2 by accessing the ...

Retrieving the source code of a specific http URL using JavaScript

Is it feasible to obtain the source code of a webpage using JavaScript on the client side? Perhaps with AJAX? However, can I ensure that the server from which I am downloading the URL sees the client's IP address? Using AJAX could potentially reveal ...

Troubles with CSS in Wordpress

Hey there! I'm currently working on some wordpress tasks and running into an issue with the code. Everything looks good in the first two sections, but the third section is displaying at the top. Please refer to the attached image for a visual of the p ...

What is the method for altering a CSS element's keyframe animation while it is currently running?

My little mouse speed detector, although not perfect, provides me with the current mouse speed every 100ms in the variable window.mouseSpeed.t. I decided to implement this feature because I wanted to create a whimsical animation at the bottom edge of the s ...

What is the most efficient method for storing and accessing a large matrix in JavaScript?

With 10000 items, creating a matrix of 10000 rows * 10000 columns using a one-dimensional array would be massive. Additionally, setting specific values to cells (i,j) where 0 < i, j < 10000 would require a large number of iterations. I am facing cha ...

What are the advantages of importing variables from components?

Let's start with some context. Our primary sass file is named main.scss, which mainly imports other scss files. /* ========================================================================== Base ================ ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

Utilizing AJAX and PHP for seamless communication, retrieve and authenticate HTTPS SSL CERTIFICATE when interacting

Recently, I successfully created a node.js REST server located at . To develop the front-end, I am utilizing a combination of html, javascript, and php. However, when I attempted to implement an SSL certificate on the front-end, a problem arose: An issue ...

UPDATE: An issue has been identified with the /login route that is currently causing an unknown error

Hours of coding and suddenly my app is rendering everything twice. Can't figure out why, please help! app.js import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import "bootstrap/dist/css/bootstrap.min.css"; ...

A JavaScript object that performs a callback function

I am delving into learning node.js and experimenting with creating a new TCP Server connection. Check out the code snippet below: var server = require('net').createServer(function(socket) { console.log('new connection'); socket.se ...

"Unlocking the potential of JSON: A guide to retrieving and displaying three specific fields in

My PHP service is returning the following data: [[1,"16846"],[2,"16858"],[3,"16923"],[4,"16891"]] Within my HTML, I have ajax set up to fetch this information; $.ajax({ type: 'POST', url: 'getDadosGrafico.php', ...

leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance. The problem at hand is related to a workout ...

Exploring Data and Models within AngularJS

I am working on a WebApp that has a unique HTML layout Nav-column-| Center Column---- | Right Column Link1---------|Data corresponding|Data Corresponding to Link1-A Link2---------| to Nav-column------| (ie based oon Center Column Link) Link3----- ...