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;
}
}