Looking to retrieve the coordinates of an element following a CSS3 translation using JavaScript?

I came across this issue in two different variations on stackoverflow, but unfortunately the proposed solutions didn't work for me.

My problem is that I need to translate an item, but when I try to retrieve its position with obj.style.left or obj.offsetLeft after the translation, I always get 0. Is there a way to accurately determine the coordinates of an element after it has been translated using CSS3?

I am unable to use jQuery, both because of restrictions and because I prefer to fully understand the solution rather than relying on a library without comprehension.

Any suggestions or thoughts on this matter would be greatly appreciated.

Thank you in advance!

Answer №1

If you want to determine the position of an element on the page, you can utilize the getBoundingClientRect() method:

Consider the following example HTML block:

<div class="centralizer popup">
    <div class="dragger"></div>
</div>

Along with the corresponding CSS styles:

body {
    background:#ccc;
}
.centralizer {
    position:absolute;
    top:150px;
    left:170px;
    width:352px;
    height:180px;
    overflow:auto;
    -webkit-transform: translateY(-50%) translateX(-50%);
    -moz-transform: translateY(-50%) translateX(-50%);
    -ms-transform: translateY(-50%) translateX(-50%);
    transform: translateY(-50%) translateX(-50%);
}
.popup {
    background:white;
    box-shadow:0 0 0 2px rgba(0, 0, 0, 0.1), 0 0 15px rgba(0, 0, 0, 0.3);
    border-radius:3px;
}
.dragger {
    background:#eee;
    height:35px;
    border-radius:3px 3px 0 0;
    border-bottom:1px solid #ccc;
}

To retrieve the accurate position using JavaScript, you can utilize the following code snippet:

var popup = document.querySelector('.popup');
var rect = popup.getBoundingClientRect();

console.log("popup.getBoundingClientRect(): \n" + "x: " + rect.left + "\ny: " + rect.top);

You can view the outcome in the following jsfiddle:

I have tested this solution on Firefox, Internet Explorer, and Chrome, and it has proven to work effectively on all my tests.

Answer №2

Hey, buckle up because this information may not be pleasant:

window.addEventListener('load', function(){
  var node = document.getElementById("yourid");
  var curTransform = new   WebKitCSSMatrix(window.getComputedStyle(node).webkitTransform);
  console.log(node.offsetLeft + curTransform.m41); //actual offset left
  console.log(node.offsetTop + curTransform.m42); //actual offset top
});

Feel free to experiment with it here:

http://jsfiddle.net/duopixel/wzZ5R/

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

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

My website layout got messed up because of Chrome version 48

Once upon a time, I created a website. Despite its outdated design, it has been functioning properly. Even though I know it's time for something new, I've hesitated to make any changes because it still works. Surprisingly, parts of the page layo ...

Utilizing string interpolation within the parameters of an AJAX call

I have a locale variable that can hold values such as en, fr, or es. The goal is to include this locale key in an AJAX request as part of the data parameter. let locale = "en"; let name = "example"; $.ajax({ url: "/path", method: "PUT", data: {chara ...

Authenticate users using JavaScript usernames

Below is my registration link that opens a modal: <a href="#registermodal" data-toggle="modal">Register Here</a> Here is the code for the modal dialog: <div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;"> ...

AngularJS directive failing to trigger event binding within the link function

Here is a plunker that you can refer to. In my project, I have developed two simple element directives, named incButtonOne and incButtonTwo. These directives are designed to track and display the number of times they have been clicked. Each directive has ...

The initial page load is experiencing issues with input type validations not functioning properly

I'm facing an issue with my text box where I only want to allow alphabets to be entered. Here is my code snippet: state ={ NomName: '', } onlyAlpha(e) { var regex = /^[a-zA-Z ]*$/; if(e.target.value === '' || regex.t ...

Guide: Positioning the Icon in the Top Right Corner of the Image

Objective: The goal is to ensure that the expand icon is always at the upper right corner of the image, regardless of its size or the responsive design in place. Challenge: I have attempted to address this issue but have unfortunately been unsuccessfu ...

The opacity attribute in CSS is not producing the desired outcome

After numerous attempts, I have yet to successfully create the desired effect on the screen I am currently working on: https://i.sstatic.net/BonQa.png My goal is to achieve a transparent effect using a gradient as a background, but so far my efforts have ...

Issue with iOS Mobile Safari Navigation Bar/Toolbar when changing orientation

Experiencing some unexpected behavior with iOS mobile safari on version 13.3. I have a website that functions as a single page application for the most part. Due to this, I have set its height/width at 100% and adjusted the content accordingly. While ever ...

Update the month in the second date picker to align with the selection made in the first date picker within the Angular framework

Is it possible to dynamically change the month of the second datepicker based on the selection made in the first date picker? Currently, it is displaying the current date by default. For example: If I select 15-10-2104 from the first date picker, the secon ...

The title of the homepage is showing up behind the AppBar. Any suggestions on how to correct this?

I encountered an issue with my appBar where the homepage was appearing behind it instead of below it. Here is a snapshot of the problem: https://i.stack.imgur.com/27LjB.png Below are the codes for the AppBar: const Header = () => { const [value, setV ...

Tips for obtaining the retrieved URL from an ajax call

How can I extract only the returned URL from an ajax request? I have tried implementing it like this: $.ajax({ type: "GET", dataType : "jsonp", async: false, url: $('#F ...

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

JavaScript - Verify if all properties belonging to an object are set to true

I'm facing a challenge with an object that contains various fields which could potentially be set to true for a user, similar to a list of achievements. If I have an object like {one: true, two: false, three: true}, how can I prevent the function from ...

The Vue component fails to refresh after modifications to the state in the Pinia store

I'm currently immersed in my inaugural vue application, focusing on constructing the login functionalities. To handle State management, I've implemented pinia. I've set up a Pinia Store to globally manage the "isLoggedIn" state. import { def ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Type Error: Issue encountered while resolving module specifier

Upon trying to import the d3.js library in a project that utilizes npm, I encountered the error message: TypeError: Error resolving module specifier: d3. This issue specifically occurred while using Firefox. index.html <!DOCTYPE html> <html lang ...

Shine a light on the input with a captivating outer

Can we replicate the outer glow effect that Safari and other browsers automatically add to an input field without using jQuery? If you want to remove it, check out this article: Thank you! ...

The Chrome developer tools are unable to locate the HttpRequest

While working in Python, I am utilizing the requests library to make a POST request to a specific URL. However, upon clicking the button, it seems that nothing is happening as per Chrome Developer Tools. No XHR requests are being made and no data is being ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...