In this tutorial, we’ll learn how we can show the position of a element using the getBoundingClientRect() and display it on the page.
Here’s our main App.vue component:
<script setup>
import { ref } from 'vue'
const targetElement = ref(null)
const positionInformation = ref(null)
const showPosition = () => {
const { top, right, bottom, left } =
targetElement.value.getBoundingClientRect()
positionInformation.value = `Position: Top: ${top}, Right: ${right}, Bottom: ${bottom}, Left: ${left}`
}
</script>
<template>
<div>
<div ref="targetElement" class="show-position" @click="showPosition">
Show position
</div>
<div>
{{ positionInformation }}
</div>
</div>
</template>
<style>
.show-position {
background-color: green;
color: white;
padding: 10px;
cursor: pointer;
}
</style>
Code language: HTML, XML (xml)
First, we initialize two ref objects named targetElement and positionInformation to be null. We’ve used targetElement to reference the div element that we want to get the position of. And positionInformation is used to display the position of the element.
The showPosition function is called when the div is clicked. This function gets the position of the div using the getBoundingClientRect() method and assigns it to the positionInformation ref.
In the template section, we define a div element with a ref attribute set to “targetElement“. A class attribute set to “show-position“, and a click event listener that calls the showPosition function when the element is clicked. The ref attribute is used to get a reference to the div element so that we can access its position. The class attribute is used to apply styling to the div element.
We also define another div element that displays the position of the targetElement using the positionInformation ref.
The style section of the component defines a CSS class named “show-position” that sets the background color to green, the text color to white, adds some padding, and sets the cursor to a pointer. The class is applied to the div element in the template section.
Here’s how the above code would look in action:
You can find a working demo of the above example from the links below: