Using javascript to determine the vertical position of an element within a fixed container

I'm facing a challenge in determining the vertical position of an element using scrollTop when the parent container has a position: fixed.

When I use scrollTop, it consistently returns a value of 0. This probably occurs because the element is no longer part of the regular flow. Am I overlooking something obvious or is there an alternative method to achieve this while maintaining position: fixed and avoiding jQuery? Perhaps there is a way to ascertain the position of an element relative to its parent?

Find below the test code snippet.

document.getElementById('target').scrollTop;
.container {
  padding-top: 1200px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: orange;
}

#element {
  background-color: green;
}
<div class="container">
  <div id="target">
    Target
  </div>
</div>

Answer №1

It is recommended to utilize the offsetTop property instead. You can find more information about it at this link.

The HTMLElement.offsetTop is a read-only property that provides the distance between the current element and the top of its offsetParent node.

console.log(document.getElementById('target').offsetTop);
.container {
  padding-top: 1200px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: orange;
}

#element {
  background-color: green;
}
<div class="container">
  <div id="target">
    Target
  </div>
</div>

Answer №2

Have you considered utilizing the getBoundingClientRect method?

The Element.getBoundingClientRect() function provides information on the size and position of an element in relation to the viewport.

var targetPosition = document.getElementById('target').getBoundingClientRect().top;

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

Is there a method to identify the quantity of audio channels within a <video> element? (HTML5)

I would like to connect an AnalyserNode to each audio channel of a video element in order to perform audio visualization. Currently, my code is functioning properly except for the fact that both AudioContext and MediaElementAudioSourceNode consistently re ...

Having trouble getting wire:click to work within an if statement in Laravel Livewire

I am currently in the process of creating a popover feature for my website that should open when I click on a phone number. Upon clicking on the phone number, it triggers a function called "startCall" in my Livewire component which sets the value of $calli ...

Combine bar and stacked bar charts on a single graph with morris.js

Can a combination of a stacked bar chart and a regular bar chart be created in morris.js? I have successfully generated a stacked bar chart using the following code: Morris.Bar({ element: 'bar-example', data: [ {x: '2011 Q1', ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

What sets apart express.Router() from using multiple express() objects?

When utilizing the latest express 4 router, it becomes possible to organize various route paths into separate files like the following example: // Inside cars.js const router = express.Router(); router.get('/brands', function(req, res) { ... } ...

Issues with Angular radio buttons are causing them to not be selected properly

When it comes to radio buttons, they should be checked based on certain conditions. <input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes <input data-ng-checked="!user.contrac ...

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

What is the process of refreshing a page post-loading?

I'm working on a fundraising webpage and I want to display the live amount of money raised. Essentially, when one user donates while another is viewing the total amount raised, I want the displayed number to update in real-time. My backend setup incl ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

The request to retrieve data from the model at http://localhost:9000/model/data.json resulted in a 404

This is the path to my directory I have a npm server running on http://localhost:9000/ to utilize the cytoscape module. However, my server is unable to locate my json file. What could be the issue with my code? This is the source code of my index.js file ...

Splitting up database results into groups of three rows and then organizing them into Bootstrap4 rows in Laravel 7

Is it feasible to utilize bootstrap rows when retrieving data from the database? I have designed a layout with 3 columns and my objective is to showcase the database outcomes in these rows. In order to display 3 rows, each containing 3 items on every page, ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

Tips for rearranging a span following an image?

Looking for a solution to rearrange a span element after an image within automatically generated HTML. Sample HTML: <span>closed</span> <img alt="Click to reset" src="xxx" class=""> Currently, the span appears before the img in the cod ...

Issues with the styling of DIV elements

Currently tackling a project that involves numerous DIVs and sections, encountering an issue with the header. When I attempt to minimize the browser window, the search bar and panes div are not staying within the "header" section as expected. The structur ...

What is the best way to include JavaScript CDN scripts in a component rather than in the index.html file?

There are three scripts located in the index.html file within the public folder: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jq ...

Unused expressions in React should not be allowed

Just dipping my toes into React and giving this code a test drive var animateButton = function(e) { e.preventDefault; //reset animation e.target.classList.remove('animate'); e.target.classList.add ...

Patience is required to await the response of the AJAX call before binding it

There is a getGeneral function that makes an ajax call using the GET method. Once the data (in json format) is received by ajax, it creates a Knockout model from the given json and returns the created Knockout model. After the Knockout model is created an ...

What are the steps to retrieve JSON data and display it using an unordered list in an HTML document?

My JSON data structure looks like this: { "fID": "00202020243123", "name": "John Doe", "List": ["Father", "Brother", "Cousin"] } When I render this JSON element in my model and view it in the HTML, everything works fine. However, when I try t ...

Adjust image size to maintain consistent dimensions

Is there a way to resize the images so they maintain the same aspect ratio? Currently, all the images are appearing distorted. https://i.sstatic.net/czpto.png Here is the HTML code for the card: <div class="container"> <div class="flex- ...