Strange occurrence with getBoundingClientRect() function and F5 refresh, what could be causing this odd behavior?

Apologies for the lengthy code, I have stripped it down multiple times to make it stand-alone. Codepen won't be helpful in this case. You can simply copy and paste the code into an HTML file to see how it behaves.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Garden</title>
</head>
<body>
<style>

#page {      
    display: inline-grid;
    grid-template-columns:auto;
    grid-template-rows: 3;
    grid-template-areas: 
    "header"
    "map"
    "footer";
}
  
#header {       
    grid-area: header;
    color: white;
    background-color: grey;
    border: 2px solid grey;
    border-bottom: none;
    border-radius: 10px 10px 0px 0px;   
    padding: 5px;  
}

#map {   
    grid-area: map;
    border: 2px solid grey;
    border-top: none;
    padding: 5px;
}   

#imagewrapper {    
    position: relative;
    border: 1px solid grey;
    padding: none;
    margin: none;
}

#mapimage { 
    display: inline;
    max-width: 100%;
    margin-bottom: -4px;
}

.pin_container {
    
    position: absolute;
    border: 2px solid grey;
    border-radius: 10px 10px 10px 10px;
    cursor: grab;
    padding: 3px;
}

#footer {
    grid-area: footer;
    color: white;
    background-color: grey;
    border: 2px solid grey;
    border-right: none;
    border-radius: 0px 0px 10px 10px;   
    padding: 5px;  
}
</style>
<div id='page'>
    <div id='header'>De Botanische Tuin Kerkrade</div>
    <div id='map' data-id='14'>
        <div id='imagewrapper'>
            <img id='mapimage' src='https://i.ibb.co/cQF07s8/map-g3-v1.png'>
            <div id='b27' class='pin_container' style='left:479px; top:792px;' data-img='map_g3_b27_v0.png'>Hubertus Borders</div>
            <div id='b22' class='pin_container' style='left:385px; top:568px;' data-img='map_g3_b22_v0.png'>De Oude Tuin</div>
            <div id='b9' class='pin_container' style='left:400px; top:400px;' data-img='map_g3_b9_v0.png'>De Thematuin</div>
        </div>
    </div>
    <div id='footer'><span class='nav_current'>De Botanische Tuin Kerkrade</span></div>
</div>

<script type="text/javascript">

    var map  = document.getElementById('imagewrapper').getBoundingClientRect();
    var pins = document.querySelectorAll('.pin_container');
    var pin;
    var div;
    var loc_x;
    var loc_y;

    for ( var i = 0; i < pins.length; i++ ) { 
        
        pin    = pins[i];
        div    = pin.getBoundingClientRect();
     
        console.log( pin.textContent+"("+pin.id+") - imagewrapper.width="+map.width+", pin_container.width="+div.width );
    }
</script>
</body>
</html>

Despite the log output looking fine when the page is initially loaded, I encounter issues upon refreshing:

Hubertus Borders(b27) - imagewrapper.width=190.93333435058594, pin_container.width=68.66
De Oude Tuin(b22) - imagewrapper.width=190.93333435058594, pin_container.width=44.64
De Thematuin(b9) - imagewrapper.width=190.93333435058594, pin_container.width=79.31

The widths of both the map and the pins seem inaccurate after a refresh. Prior to simplifying the code, different results were observed when using ctrl+f5. It's challenging to pinpoint the exact cause of this erratic behavior. Testing across Chrome and Firefox browsers shows inconsistent outputs. Chrome consistently displays incorrect values even with a fresh load or forced reload.

While the rendering appears as expected visually, regardless of the browser or action taken, the centering script utilizing getBoundingClientRect() gets disrupted.

Any insights on what might be causing this?

Answer №1

The issue is not caused by the image loading late, but rather it indirectly triggers it.

To replicate the problem, simply execute the loop provided in the code a second time in the console.


Instead of providing a direct answer, this explanation delves into the issue.

We are facing a scenario with absolutely positioned elements which lack intrinsic dimensions and rely on their content, such as text, making them unpredictable.

When applying positioning to an element using properties like top, bottom, left, or right, the movement stops at the edges and starts shrinking instead of moving until it reaches the limit set by the longest word.

This behavior explains what is occurring here: before the image loads, the parent's width is smaller causing the elements to be positioned beyond the left edge, resulting in shrinkage based on certain width values. After the image loads, the parent's width increases, affecting the elements' widths accordingly.

A potential solution could involve defining a fixed width/height for the positioned elements or utilizing white-space: nowrap.

Given uncertainty about how your application will scale, providing a permanent solution may be challenging if setting a width/height is undesirable.

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

How can I add margin to an anchor using CSS?

My header has a fixed height of 50px. Within the body of my page, there are numerous anchor links. However, when I click on these links, the anchored content appears underneath my fixed header, causing me to lose 50px of visible content (requiring me to sc ...

Show the picture stored in the S3 cloud storage

I'm facing an issue with displaying images uploaded to S3. I've checked the permissions and can access the URL successfully to retrieve data. However, when I insert the URL into an image tag, it shows up as a broken link. Upon inspecting the net ...

Ways to prompt for user input using JavaScript

How can I collect user input using JavaScript for a website that saves the input into a text file? Below is the code I am currently using: <button type="button" onclick="storeEmail()">Enter Email</button> <script> ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

Creating a clear distinction between a logo and accompanying text

I'm working with bootstrap 5 and I want to add a subtle line right after the logo.png below. The line should be directly connected to the logo with no spaces, and also no spaces between the text and the line. <!-- Bootstrap-5 --> <link hre ...

Command handler that dynamically utilizes both shared and separate commands

Currently, I am in the process of setting up a command handler for multiple channels on Twitch. To organize the commands, I have them divided into specific folders for each user and generic ones. Accessing these commands is done by using a map(). My goal i ...

Struggling to implement Google OAuth in a MERN stack - facing a 400 bad request error with the package @react-oauth/google

Here is the React form and relevant code sections for the issue: import { useGoogleLogin } from '@react-oauth/google'; const SignUpForm = () => { const navigate = useNavigate(); const [name, setName] = useState(""); const [email, setEm ...

Utilizing R to Retrieve the Date from an HTML Element

I've been exploring ways to extract dates from an online community using the R programming language. As a newcomer to R, I've been facing challenges with the R package that seems to retrieve a long list instead of a specific date or time. I atte ...

What is the best way to have react-bootstrap's Dropdown automatically open when hovering your mouse over it?

Looking for a simple solution. I want the dropdown to open when hovering over it, rather than clicking on it. Here is my current code: <Nav> <NavDropdown onMouseEnter = {()=> isOpen=true} open={isOpen} noCare ...

How can I adjust the size of an element without causing the other elements to move around on the

Currently, I am working on a live web page. You can view it at the following address: The issue I am facing is with the element just before the body's closing tag, the div "games_grid." When hovering over the game capsule image, it expands, causing t ...

Using PHP to detect changes in input fields upon page load with jQuery

I have a jQuery snippet on my page: $( document ).ready(function() { $("#URL").on("input load", function(e) { console.log(e.type) .... }); }); Further down the page, I also have... <input id="URL" type="text" value="<?=$_GE ...

Loop through the array only if the property exists to avoid encountering the 'cannot iterate over undefined' error

Here's a code snippet that I'd like to simplify: if (this.props.fk_data) { if (this.props.fk_data.length > 0) { for (let fk_dataset of this.props.fk_data) { } } } I'm considering putting this.props.fk_data into st ...

Accessing a distinct element of e.parameter

I've implemented a Google App Script on my website that automatically writes form data to a spreadsheet upon submission. With multiple forms on the site, I want all their data to go to the same Spreadsheet but different 'Sheets' (tabs at th ...

What are some alternative ways to link a local MongoDB database to my Android Studio application instead of using MongoLab?

Can someone please help me figure out how to connect my Android Studio project to a MongoDB database stored locally on my PC? I've been searching for solutions that don't involve using MLab, but I haven't had any luck. I've attempted f ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Why is the 'name' property used in the export default{} syntax?

Vuejs is my current learning focus, and one thing that puzzles me is the necessity of this particular name. <template> </template> <script> export default { name: 'NotFound' } </script> <style> </style&g ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...