Obtain the in-flow position of a DOM element

alert("Incorrect (red): " + document.getElementById("target").getBoundingClientRect().top);
alert("Proper (blue): " + document.getElementById("wrapper").getBoundingClientRect().top);
#target {
  transform: translate(20px, -20px) rotateZ(20deg);
  background: red;
  width: 50px;
  height: 50px;
}
#wrapper {
  background: blue;
  display: inline-block;
}
Text
<div id="wrapper">
  <div id="target">
  </div>
</div>
more text

In the scenario described above, the blue square occupies the exact position that the red square would have if it did not have a transform. It also takes up the space and location that the red square holds as an in-flow element. The JavaScript position I aim to obtain is for the blue square. The hurdle I face is that my initial code lacks a #wrapper element which I cannot create. How do I retrieve the in-flow position of an element that may or may not be at that position (due to transform, position: relative;, or other factors)?

I am open to both Plain JS and jQuery solutions. However, I prefer a concise solution rather than a lengthy one exceeding 50 lines.

My attempts:

  • jQuery('#target').offset(): Considers the transform (returns a negative value in the example above).
  • document.getElementById('target').getBoundingClientRect()
    : Similar to jQuery's offset.
  • jQuery('#target').position() with traversal through offsetParent: Currently functional but this aspect of jQuery may be considered a bug or subject to future changes, as per information on this site.

Answer №1

Utilize the WebKitCSSMatrix function.

var element = document.getElementById("target");
var currentTransform = new WebKitCSSMatrix(window.getComputedStyle(element).webkitTransform);
console.log(element.offsetLeft + currentTransform.m41); //actual offset left
console.log(element.offsetTop + currentTransform.m42); //actual offset top

Compatibility with Browsers:

  • Refer to this response for handling browsers that do not support the WebKitCSSMatrix functionality.

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

Upon clicking the navbar dropdown item, it shifts its position

I am currently working on setting up a navigation bar with multiple items aligned to the right side. However, I have encountered an issue where clicking on the "notification" icon causes the other icons in the navbar to move instead of remaining fixed in p ...

Determined Worth of Chosen <Datalist> Option

Currently, I am utilizing an <input type='text'> Element in conjunction with a <datalist> to suggest user names for a form. The functionality is working correctly and all my users are displayed. However, upon form submission, I need ...

We encountered a problem while trying to create the route "/": Minification of HTML failed in Nuxt js

After successfully developing a Nuxt app that runs perfectly with "npm run dev," I encountered an error when generating the site using "npx nuxt generate." Despite my efforts, I cannot locate the source of the error. Any assistance would be greatly appre ...

Sentry platform is failing to record network-related problems

Incorporating Sentry into my Next.JS application has allowed me to easily detect JavaScript errors such as reference or syntax issues on the Sentry platform. Unfortunately, I have encountered some challenges as Sentry is not logging any network-related er ...

Tips for creating CSS3 animations in Angular triggered by mouse clicks

I'm working with a span that utilizes a Bootstrap icon. My goal is to fade out and fade in the same element (span) on click, while toggling the class (icon). There's a boolean variable called showLegend which determines whether or not to animate ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

Steps for adjusting the margin of a section using the p tag

Newbie CSS inquiry here... Here's what I currently have in my stylesheet: #topheader { position: absolute; width: 100%; height: 100px; background-color: #D1E6DA; font-size: 200%; } I want to include the following: p { margi ...

I have a page division with scroll bars and I want to ensure that the entire content of the division is displayed

I am facing an issue with a div and table on my webpage: <div id="tablediv"> <table id="table"> <tr><th>headers</th></tr> <tr><td>contents</td></tr> </table> <d ...

I am experiencing difficulty with the color of my progress bar in Firefox

After successfully creating an interactive progress bar that works perfectly in Google Chrome and surprisingly also in Safari without vendor prefixes, I encountered a roadblock when testing it on Firefox. The progress bar color reverts back to the default ...

Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows: computerName | flagId computer1 | ...

extract the information from a specific div on a different website using JavaScript

My goal is to load a specific div with a class="container" from a website and extract its content into my application. Upon making an ajax call to retrieve the site's data, I encountered a cross-domain origin error since I don't have access to t ...

The datatable does not adjust to changes in page size

My jsfiddle example showcases different card boxes, and I am currently focusing on making the 'Table 1' box responsive. However, I have encountered an issue: Check out my jsfiddle example here code If you open the jsfiddle with a large enough ...

Raycasting is functioning properly on objects created within the program, however, it seems to be ineffective on imported OBJ models

As a newcomer to three.js, I am currently exploring raycasting and encountering some confusion regarding its functionality with imported 3D models. Specifically, when I import an obj model and attempt to determine if there is contact with the imported 3D ...

FNS Date-Timezone Abbreviation

Is there a way to shorten the Australian Eastern Daylight Time abbreviation to just AEDT? When I use it currently, it displays as 11/11/2022 15:29:25 Australian Eastern Daylight Time. I would like it to show as 11/11/2022 15:29:25 AEDT import { formatInT ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Can the `lang` attribute be used in a `style` tag to specify the CSS preprocessor language for VueJS? Are there any disadvantages to using this method?

Occasionally, I notice people incorporating code like this: <style lang="scss"> ... </style> <style lang="stylus"> ... </style> I checked the documentation for the style tag and found that lang is not a valid a ...

"I am facing an issue where the button does not appear centered after using jQuery

I can't help but notice that when applying CSS directly, my buttons end up centered horizontally. Yet, when I insert the same code using append(), the buttons seem to align towards one side instead. Here is the HTML/CSS code snippet: <div style=" ...

Can text be inserted into an SWF file using ASP.NET or Javascript via an online platform?

I am managing a website that features videos created by a graphic designer who updates and adds new content regularly. I am looking to add dynamic text to these videos after a specific amount of time, such as "Hosted by XXX". However, I am hesitant to ask ...

Utilizing JavaScript within a WordPress loop

I'm facing an issue with running JavaScript within my WordPress loop where it doesn't seem to recognize the PHP variables. My goal is to create a functionality where clicking on one box reveals hidden content, and clicking on the same box or anot ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...