Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property that can help me achieve this.

The use of .offsetLeft is not suitable for my requirements as the element is nested inside parent elements with position: relative.

Feel free to take a look at my codepen here: https://codepen.io/mister-hansen/pen/aGdWMp (This includes an example illustrating the impact of different positions: relative settings.)

HTML

 <div id="app">
  <div class="box">
    <div class="box__in" ref="my_box_a">
      What is my current position?
      <br> offsetLeft: <strong>{{posBoxA}}</strong>
    </div>

  </div>
  <div class="box box--relative">
    <div class="box__in" ref="my_box_b">
      What is my position within the relative box?
      <br>
      offsetLeft: <strong>{{posBoxB}}?!</strong>
    </div>

  </div>
</div>

Javascript (VueJs)

const app = new Vue({
  el: '#app',
  data () {
    return {

      posBoxA: 0,
      posBoxB: 0,
      }
  },
  mounted () {
    this.calcPosOfBox()
  },
  methods: {
    calcPosOfBox () {
      this.posBoxA = this.$refs['my_box_a'].offsetLeft

      this.posBoxB = this.$refs['my_box_b'].offsetLeft

    }
  }
})

CSS (SCSS)

html, body {
  margin: 0;
}

#app {
  padding: 10vh 100px;
  font-family: sans-serif;
}

.box {
  margin: 0 auto 10vh;
  padding: 10vh 50px;
  background: lightgrey;

  &--relative {
    border: 1px solid red;
    position: relative;
  }

  &__in {
    padding: 1rem;
    background: lightgreen;
  }
}

Answer №1

For obtaining the position of an element, you can utilize the getBoundingClientRect() method. The values returned for x and y are relative to the top-level viewport.

Highlighted section:

The result is a DOMRect object that encompasses the rectangles fetched by getClientRects() for the element, essentially representing the CSS border-boxes linked with the element. The outcome is the smallest rectangle that encloses the entire element, with read-only properties like left, top, right, bottom, x, y, width, and height detailing the overall border-box in pixels. All properties except for width and height are with respect to the top-left corner of the viewport.

const app = new Vue({
  el: '#app',
  data() {
    return {

      posBoxA: 0,
      posBoxB: 0,
    }
  },
  mounted() {
    this.calcPosOfBox()
  },
  methods: {
    calcPosOfBox() {
      const boxABB = this.$refs["my_box_a"].getBoundingClientRect();
      const boxBBB = this.$refs["my_box_b"].getBoundingClientRect();
      this.posBoxA = boxABB.x;
      this.posBoxB = boxBBB.x;

    }
  }
})
html,
body {
  margin: 0;
}

#app {
  padding: 10vh 100px;
  font-family: sans-serif;
}

.box {
  margin: 0 auto 10vh;
  padding: 10vh 50px;
  background: lightgrey;
}

.box--relative {
  border: 1px solid red;
  position: relative;
}

.box__in {
  padding: 1rem;
  background: lightgreen;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ee8ebfbdeacb0abb0afa8">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
  <div class="box">
    <div class="box__in" ref="my_box_a">
      What is my position?
      <br> offsetLeft: <strong>{{posBoxA}}</strong>
    </div>

  </div>
  <div class="box box--relative">
    <div class="box__in" ref="my_box_b">
      What is my position in relative box?
      <br> offsetLeft: <strong>{{posBoxB}}?!</strong>
    </div>

  </div>
</div>

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

Unlocking the full potential of parsing messages using google protobuf-js

Currently, I am developing a front-end application using Angular5+ that utilizes google-protobuf JS and WebSocket for backend communication. Within my .proto files, I have defined 2 objects: a Request object. a Notification object. I have created a han ...

Pinia alert: The function "getActivePinia()" was invoked without an active Pinia instance. Could it be possible that you overlooked installing Pinia?

Despite having an action that dynamically updates the 'pending' state based on whether the data has been fetched, reactivity seems to be non-functional when used inside the component. This issue is referenced in the official Pinia documentation: ...

Seeking assistance with setting up BxSlider installation

I'm struggling with adding bxslider to my HTML template. No matter what I try, the slider doesn't work as expected. When I preview my website, all three images are displayed together in a single column. Can someone please guide me on how to fix t ...

To enable RTL in TextField, please note that the JssProvider is only available in "react-jss/src/JssProvider" and not in "react-jss/lib/JssProvider"

Seeking help to convert LTR to RTL in the following code: <TextField id="date" label="EmployeeDate" type="date" onChange= ...

The challenges with implementing makeStyles in React Material UI

const useStyles = makeStyles((theme) => ({ toolbarMargin: { ...theme.mixins.toolbar, marginBottom: "3em", }, logo: { height: "7em", }, tabContainer: { marginLeft: "auto", }, tab: { ...theme ...

When using a custom selection color to highlight underlined text, the underline becomes invisible

I am currently working on a website where I want to customize the text selection color. ::selection { background-color:#00ffff; } However, there seems to be an issue in this specific situation: p::after { content:"Try selecting the above elemen ...

jQuery slide adjusts the width of the slide as it transitions

The script is running smoothly. Check out the jsFiddle here The issue lies in its width adjustment when sliding (clicking "here"). It seems to be cutting off the width related to a 100px margin-left in #slider. Why does it seem to "jump" and how can this ...

Creating duplicates of a parent mesh in THREE.js with its children and additional materials

I am inquiring about a cloning issue I am having with a mesh that has a parent and 4 children, each with different materials. When I clone the parent mesh using this code: let result = cloudObjects.sideCloudGeometry[texture].clone(); The cloned mesh look ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Achieving a layout of three columns and two rows (1 x 2 x 2) using flexbox

I am looking to achieve a specific layout using Flexbox. While I am comfortable with CSS, I want to challenge myself by learning how to implement this design using Flexbox for more concise and maintainable code. https://i.stack.imgur.com/QDVfT.png .ban ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

What is the best way to access the camera of a mobile phone through a web application?

Whenever I try to access the camera on my mobile device through a web app, I encounter an issue. While the camera works perfectly fine on the web version, it fails to show up on my mobile device unless I add https:// in the URL. How can I resolve this prob ...

Functionality of retrieving arrays from PHP via jQuery ajax (JSON) runs smoothly, however encounters issues specifically on web server

No solutions have been able to solve the problem at hand despite finding similar questions. function loadProject(id) { $.ajax({ url: 'loadDrumsetData.php', type: 'GET', data: { i: id }, ...

What is the functionality of this pseudo element?

I am interested in understanding the purpose of the pseudo element and how it affects the layout without altering the existing markup. Check out the code demo div{ border: 1px solid #000; height: 300px; } div:before{ content: ""; ...

Transform the date to match the user's preferred timezone abbreviation

I am currently utilizing the momentJS library for timezone conversion logic within my JavaScript code. I retrieve the User Preference Timezone abbreviation from a web service response, but when attempting to convert the date using the Timezone abbreviation ...

Unlocking the power of Vue by inheriting JSON

JSON data { "text_color": "blue", } After fetching the color from JSON, I need to dynamically set it as the font color for an HTML element. <h3 style="color:{{data.text_color}}">Example</h3> ...

Incorporate the AngularJS controller into your JavaScript code

I am facing an issue with my jQuery UI dialog that contains a dynamic <select> populated with Angular and AJAX. The problem is that the AngularJS script still runs even when the dialog is not visible. To solve this, I added a condition to stop the s ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Responsive grid columns in Vuetify that adapt based on the screen breakpoint

My goal is to make the columns responsive and adjust based on changes in breakpoint sizes: https://i.sstatic.net/UbgCm.jpg https://i.sstatic.net/rciLy.jpg https://i.sstatic.net/SwscL.jpg I am really struggling to figure out how to implement this logic ...