Locate the X and Y coordinates of an inline element in JavaScript in order to position a popup box beside

I currently have a table with a few records and I am looking to implement a feature where a popup box appears when the user hovers over a specific record.

The popup box has already been created and the message has been set. The only remaining task is to position the box (

<div id="popup"></div>
) so that it appears next to the element that triggers it.

To achieve this, I need to obtain the coordinates of the element that triggered the event. However, using this.offsetLeft gives me relative coordinates which are not helpful in my case because the element is inline.

Since I am using pure JavaScript for this project, I prefer solutions that do not involve jQuery. Any advice on how to accurately determine the location of the element would be greatly appreciated!

Answer №1

const container = this.getBoundingClientRect();

alert( "Y position:" + container.top + "X position:"+ container.left );​

Check out this JSFiddle link for more information.

If you need to factor in scrolling:

const body = document.body,
    html = document.documentElement,
    scrollTop = window.pageYOffset || html.scrollTop || body.scrollTop || 0,
    scrollLeft = window.pageXOffset || html.scrollLeft || body.scrollLeft || 0,

    box = this.getBoundingClientRect(),

    top = box.top + scrollTop,
    left = box.left + scrollLeft;

alert( "Adjusted Y position:" + top + "Adjusted X position:"+ left );​

Answer №2

If you want to find the element's position relative to the page, one approach is to recursively traverse through its offsetParents and add up their offsetLeft values.

Here's a sample function that demonstrates how this can be achieved:

function calculateOffsetLeftRelativeToPage(element) {
    var offset = element.offsetLeft;
    var offsetParent = element.offsetParent;
    if (offsetParent != null) {
        offset += calculateOffsetLeftRelativeToPage(offsetParent);
    }
    return offset;
}

var primaryElement = document.getElementById('primaryElement');
var secondaryElement = document.getElementById('secondaryElement');

primaryElement.onmouseover = function() {
    var offsetLeft = calculateOffsetLeftRelativeToPage(this);
    secondaryElement.style.left = offsetLeft + 'px';
}

Check out the JSFiddle demo for a practical illustration: jsfiddle.net/e6vWV/

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

Could someone assist me in resolving the issue of receiving empty emails from my online form submission?

Every day, I receive 6 blank emails from my contact form at the same time. Even though the form on the website is filled out correctly and all the information goes through, I still get these mysterious blank emails. I have implemented validation checks in ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Static compression in Express.js is failing to gzip the CSS and JavaScript files

I have created a basic server using Expressjs with the following code: 'use strict'; var express = require('express'); var app = express(); var compression = require('compression'); app.use(compression()); app.listen(process ...

The Div element refuses to budge from its current position on the page's layout

$("#pg2_main_display_div ").css({ top: -$("#pg2_main_display_div").offset().top }); The value generated by -$("#pg2_main_display_div").offset().top is currently -1033. Unfortunately, this code does not seem to be functioning properly as the content ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

`Incorporating JavaScript for Menu Navigation on the Homepage: Challenges Ahead`

I am attempting to modify the HTML link within the Javascript on the thank you page, but my attempts to change all respective pages' HTML links to index.html/javascript:goTo(XXXX) have been unsuccessful. How can I successfully alter the link to conne ...

showing the angular response data in a HTML table layout within a specific div element

I'm currently using the angular-fullstack generator and I've received data in response to a GET request in the form of integer values (1, 2 5, 6 134, 245 236, 567 415, 234 and so on). I'd like to display these values in an HTML t ...

Steps to resolve the days.map error:

My map function is, days.map((val)=>val) Upon consoling the days prop, I receive the following output: [Array(7)] 0: (7) ['', '', '', 'Wednesday', '', '', 'Saturday'] length: ...

Maintaining Login State in Django REST API After Page Refresh

Struggling with maintaining login status when using DJANGO Rest API and an AngularJS client. Despite having authtoken and default auth classes set up, including 'rest_framework.authentication.TokenAuthentication' and 'rest_framework.authenti ...

Issue with Bootsrap 4 Dropdown Menu Displaying Incomplete Links

There seems to be an issue with the Bootstrap 4 dropdown menu not displaying all the links. Please refer to the image below: https://i.sstatic.net/ZS2t2.png The dropdown menu is not showing beyond the red band. I can't seem to figure out what I&apos ...

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

How can you identify English words along with non-English characters and special characters using JavaScript regex?

Dealing with a text that consists of English and Chinese characters can be tricky. I need to separate out the English words, foreign characters like French or Chinese, numbers, and special characters such as "@#$%^&>?", so that I can manipulate them ...

There is no native WebCrypto implementation available in the current environment when accessing a Next.js app using an IP address

When accessing my Next.js app from 127.0.0.1:8082 or localhost:8082, everything runs smoothly. However, if I try to access it using my machine's IP address (e.g. http://10.233.xx.xx:8082/), an error is thrown stating Error: no native implementation of ...

Shading different elements within an illustration

Interested in developing a clothing customization tool where users can change the colors of an image of clothing. Is it feasible to achieve this using HTML5 or Javascript? Any helpful advice on how to get started would be greatly appreciated. ...

The functionality of $watch is not functioning correctly within the Modal, despite implementing it with $scope.user={pwd1:''}

For the Plunker link referenced, please click here: http://plnkr.co/edit/0vOjw0?p=preview index.html <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css"> ...

Dealing with recursion issues. What are effective solutions?

Having a small issue with my recursion. I've created a function that checks for matching directions of clicked boxes. const checkMatchingDirections = (board, r, c) => { const top = board[r - 1] !== undefined && { row: r - 1, column: c }; ...

The google.maps.LatLng() function seems to only accept direct values as parameters, as using variables does not seem to work

My goal is to provide source and destination inputs and then display the direction between them, but I am facing an issue with google.maps.LatLng() function. It does not accept a variable as a parameter. When I pass hardcoded values like google.maps.LatLng ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

Modifying HTML content with the power of jQuery

I have an HTML code snippet that looks like this: <td id="myColumn" class="Column"> Old Data </td> With jQuery, I'm attempting to update the content from "Old Data" to "My New Data". I've tried using the following methods: $( ".Col ...

Tips for creating a column with add, edit, and delete buttons in PHP

I found this code on a website that handles pagination and search functionality. However, I am looking to enhance it by adding an icon or button in a column that will allow users to link to the edit and delete functions for specific data selected in the ta ...