Finding the precise top offset position with jQuery upon scrolling – a step-by-step guide

I need help with detecting the offset top of a TR element when it is clicked. It works fine initially, but once the page is scrolled, the offset().top value changes. How can I resolve this issue?

$(function() {
  $('tr').click(function() {
    offsetTop = $(this).offset().top;
    console.log(offsetTop);
  });
});
.myDiv {
  overflow-y: auto;
  height: 250px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="myDiv">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650f0a0d0b25001d04081509004b060a08">[email protected]</a></td>
      </tr>
      ...
      <tr>
        <td>July 10</td>
        <td>Dooley</td>
        <td><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f399869f8ab3968b929e839f96dd909c9e">[email protected]</a></td>
      </tr>
    </tbody>
  </table>
</div>

Answer №1

One way to determine the offset is by taking into account the current scroll position:

let topOffset = $(selector).offset().top - $(window).scrollTop();
let leftOffset = $(selector).offset().left - $(window).scrollLeft();

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

In the event that the "li" element contains an "

<ul> <li> <ul></ul> </li> <li></li> <li></li> <li></li> <li> <ul></ul> </li> </ul> Is there a way to specifically a ...

Separate sentence to one word per line

Can CSS be used to display each word of a sentence on a separate line? Input: <div>Hello world foo bar</div> Rendered output: Hello world foo bar It is not ideal to set the width to 1px, as specified. ...

Can you show me the steps for downloading the WebPage component?

My goal is to save webpages offline for future use, but when I download them as html many of the included components disappear! I attempted opening them in a WebBrowser and downloading as html with no success. One potential solution is to download the ht ...

Struggling to insert a span element into an anchor tag within a dynamic WordPress navigation menu

I am currently attempting to insert a span tag within a tags in the secondary navigation located on the second level of the following page URL. Thus far, I have only discovered methods for adding span tags to the main navigation as well as child and grand ...

React is having difficulty locating a specific module

I've been attempting to install the parallax library from https://github.com/wagerfield/parallax/. I have gone through the documentation and even found a sample usage in JavaScript. Planning to integrate it into React, based on the sample code and Rea ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

Removing Delivery Address and Method From Checkout Page in OpenCart 2

Is there a way to remove "Step 2, Step 3: Billing Details" from the Checkout Page in OpenCart 2.0? I have searched for solutions online but haven't found one specifically for OpenCart 2.0. This is what I tried: <div class="panel panel-default" s ...

Error Code - WCF communicating with jQuery Post

Whenever I try to access the Stats from my WCF Service, I keep getting a Bad Request Error 400. Even after removing the date parameter and checking for potential causes, the error persists. function WCFJSON() { //var now = new Date(); //var getFromDate = ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

What could be causing the "undefined property read" error even though the data is clearly defined?

export async function getPrices() { const res = await fetch( "https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290" ); const quote = await res.json(); return { props: { quote } }; } export de ...

Connect the input field to a dictionary

Here is an input field: <input id="DeviceId" class="form-control deviceCatalog" data-bind="value:DeviceTemp, valueUpdate: ['blur']" required /> This input is connected to the following viewModel: var ViewModel = f ...

Canvas only draws outside the table, with the exception of the first one

I am facing an issue with placing multiple signature pads inside table cells. Only the first canvas gets drawn, while the others remain blank. I have checked the mouse/touch events. The events are triggered (up/down/move) and the draw function is called, ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Leverage the power of Next.js Dynamic routing query object with an SWR fetch request

While working with Next.js dynamic routing, I am facing an issue where my SWR fetch request is being called before the query object is properly set. This occurs specifically when using the routing query object. Let's take the example of a dynamic rou ...

Is there a way to detect when the user closes a tab or browser in HTML?

I am currently developing a web application using the MVC architecture and I need to find a way to detect when a user closes their browser tab so that I can destroy their session. My tech stack includes jsp (html, js) and java. Any suggestions on how to ...

Updating a URL for all users using React/Next.js and Firebase: a guide to refreshing the page

I am currently developing a Next.js application with a Firebase backend and have encountered an issue. In my setup, users can create sessions that others can join, but only the creator of the session can "start" it, triggering a state change. I need all us ...

Ways to prevent horizontal scrolling in an image

Currently, I am working on a scrolling animation page that is optimized for mobile devices. One issue I am encountering is when an element is larger than the screen size, such as when an image is wider than the mobile device. In this scenario, the user can ...

Node app experiencing port exhaustion within Azure Function

Currently, I am in the process of developing an Azure Function that is responsible for making a high volume of outgoing HTTP requests. However, I have noticed that periodically it reaches a limit where all requests time out for a brief period of a couple m ...