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

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Unable to click on element in Firefox browser

Encountering an issue with the following error message: Element is not clickable at point (791, 394). Other element would receive the click: Command duration or timeout: 66 milliseconds Any ideas on what's causing this? Using selenium web driver ve ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

Unexpected values being returned by Javascript/jQuery variables

Struggling with understanding scope in JavaScript, like many others before me. It can be quite challenging to navigate through the code at times. I've reviewed previous discussions on this topic, but I'm still having trouble applying it to my spe ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

Submit button remains inactive even after submitting form via ajax request

I have a page with multiple forms on it for a CRM that I am developing and each form is properly named, but I am facing an issue where the submit button remains disabled after making a $.post() request. Here is my universal post handler for form submissio ...

Assistance needed in keeping an image with absolute positioning CSS fixed to the top left corner of the browser

Looking for some CSS help as a beginner here! I've been trying to position a transparent PNG image over a centered table, but it seems stuck in the upper left corner of the browser. Absolute positioning should give me freedom to move it around, right? ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method. const customers = [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: ' ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Press and hold feature using CSS or JavaScript

When working with a jQuery draggable element, my objective is to change the cursor to a move cursor when clicking and holding the header. I have attempted using CSS active and focus properties, but so far no changes are taking place. ...

Radiant Curvature Background Gradient

On my website, I'm trying to replicate the unique background gradient found here. Unlike a basic linear gradient that can be easily repeated as an image to fill any length, this one poses a challenge. Can anyone share a technique or method to help me ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...

I am interested in utilizing a variable's value as an ID within a jQuery function

When working with jQuery, I often use a variable to store values. For example: var x = "ID1"; To utilize the value of this variable as an ID in my jQuery functions, I simply concatenate it as shown below: $('#' + ID1).val(); Thank you for you ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

NextJS compilation sometimes results in undefined errors when using Sass styles

My peace lies in the sass code: .link display: inline-table text-align: center align-self: center margin: 5px 15px font-size: 20px color: black text-decoration: none transition: 0.1s ease-in-out .link:hover text-decoration: underline .l ...