At what point can we rely on the accuracy and timeliness of Element.getBoundingClientRect?

I am currently in the process of developing some code that utilizes Element.getBoundingClientRect (gBCR), combined with inline style updates, to carry out calculations. This particular project is not intended for a general website, so I am not interested in exploring "better CSS methods" for this specific task.

The JavaScript operates synchronously and follows these steps:

  1. Retrieve the gBCR of the parent element
  2. Conduct calculations;
  3. Update inline CSS styles (such as size and margins) of a child element belonging to the parent
  4. Retrieve the gBCR of the parent element again

Can I be certain that the calculated client bounds will reflect the new bounding rectangle of the parent at step 4?

If not ensured by a specification, are modern browser implementations likely to provide this assurance? If so, what exceptions should I be aware of if it's only "mostly guaranteed"?

No elements are being added to or removed from the DOM, and the elements undergoing modifications are direct children of the parent node; pertinent information to consider.


1"Modern": UIWebView (iOS 6+), WebView (Android 2+), and common versions of Chrome/WebKit, Firefox, IE9+, including their mobile counterparts.

Answer №1

Having some trouble with gBCR reliability on ios8.4.1/Safari8.0.

One method is to create a large div at the top of body (gBCR set to 0) and scroll to the bottom (resulting in a negative gBCR value). When you resize the div to 1x1, the window.scrollY should automatically reset to 0. Ideally, gBCR should also be reset to 0 but sometimes stays as a negative value. By using setTimeout, after 200ms you can confirm the correct value being 0.

Answer №2

The issue of an old question has been lingering in my mind, and while searching for answers, I stumbled upon this very question. It may be beneficial to others as well.

After much exploration, the most reliable solution I found to ensure that getBoundingClientRect() functions correctly is by triggering a refresh at the top of the window, calculating positions, and then returning to the user's original location.

A sample code snippet would resemble:

  scroll_pos = document.documentElement.scrollTop // save current position
  window.scrollTo(0, 0); // move to the top

  v_align = parseInt(el.getBoundingClientRect().top) // demonstration of gBCR for vertical alignment
  //... any additional code necessary
  window.scrollTo(0, scroll_pos); // return to initial position

This process typically happens quickly and smoothly, ensuring minimal disruption to the user experience.

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

I seem to be encountering a recurring issue with a jinja variable when trying to create an onclick function

Why do I keep encountering this error message: Uncaught SyntaxError: missing ) after argument list (at bestellen:60:105) This is the HTML code causing the issue: <div class="gerechten"> {% for gerecht in gerechten %} <div ...

Hovering over the Laravel Breeze dropdown will activate a dropdown feature

Recently, I've been working on a project with Laravel Breeze and have been utilizing some default components. The dropdown component used in the navigation bar caught my attention. By default, it requires a click for the menu to drop down below. Howev ...

What happens when WebGL crashes while browsing a webpage?

One of my applications utilizes WebGL with the Three.js library, but occasionally crashes. Is there a way to catch these errors using a plain JavaScript or Three.js event? Currently, I am only listening on the window.onerror event for any errors. ...

Position several elements in alignment within Bootstrap columns on a single row

Looking for a way to align multiple items horizontally across two columns within a row in Bootstrap? Check out the sample HTML code below: <div class="container"> <div class="row"> <div class="col-sm-6"> <h1>Short Hea ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

Dynamically import React Material UI Icons when needed

The concept here revolves around importing react material UI icons only when necessary, especially in situations where we may not know the icon name during compile time. (Ensuring that we have valid icon names) My method involved using a require statement ...

Unraveling the Mystery of CSS3 or JavaScript Sliders

I am currently developing a new website and I was intrigued by the slider effect on Apple and IBM's websites. For reference, you can check out how it works on sites like: and I noticed that the text and images slide in opposite directions, which se ...

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

unusual occurrences with JavaScript - debugging on Google Chrome

There's a bizarre issue happening in my code. An object is being sent correctly by the server, and it's arriving in my angular factory just fine. However, when I log the object, something strange occurs: https://i.sstatic.net/S6WvC.png When the ...

Using the Twit package on the client side: a step-by-step guide

I have been utilizing the Twit package for searching tweets. After executing the js file in the console, I am able to see the tweets but when trying to use them on my webpage, an error 'Uncaught ReferenceError: require is not defined' pops up. Th ...

Issues loading SVG pattern textures with PHP

While experimenting with SVG and PHP codes, I encountered a frustrating issue that has me stumped. I have an SVG image containing some shapes. Using the fill attribute and the def tag, I can easily apply textures to specific shapes using a simple GET var ...

What is the best way to incorporate PHP code within a JavaScript function?

Is it possible to dynamically append the uploaded file name to the list displayed in ('.list')? The challenge lies in passing $_FILES["fileImage"]["name"] as an argument to a separate JavaScript function for appending, especially since the PHP sc ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...

React-big-calendar: Customize day view to end at 1 am for multiple days

I'm currently in the process of developing a booking system and utilizing react-big-calendar for this project. Situation: A business operates from 9am to 2am the next day, allowing clients to book appointments between 11pm and 1am. Objective: To sho ...

Issue with .get() method in jQuery affecting IE7, IE8, and IE9

While testing the sending and receiving of data to a PHP file using jQuery, I encountered an issue with Internet Explorer (I am using IE9, but I also checked on IE8 and IE7). When I click on one of my divs, I send an "ID" to the server and the PHP file re ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Flexbox does not support sub-columns

I'm having trouble integrating these two columns along with their sub-columns. I have to resort to using this structure instead: <div class="custom_classes"> <div class="custom_classes">col1</div> <div class=&q ...

How can I implement user flow using AngularJS?

We're facing an issue with implementing UserFlow in our AngularJS app. Our product is built on older version of AngularJS (1.8) and although we find the concept of UserFlow appealing, we are running into a problem. The standard injection and initiali ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

A guide on leveraging refs to set props in React JS

Is it possible to change props in my component using refs in react js? <MyComponent ref={'input1'} name={'input1'} label={interestsName} disabled={ false} onChange={this.myFunction}/> After the onChange event, I call a ...