Is there a way to determine the dimensions of an HTML element? (taking into account added elements)

It seems that the current situation is not feasible at this time.

I am working on an animation that requires an element to move from an absolute position to an inline one. The challenge is that I cannot predict how the container or the element itself will be sized.

The main thing I need to figure out is what the size of the HTML Element will be after the transformation, without any flickering or jittery effects.

This task becomes very complex (and perhaps impossible) because I have no way of knowing whether adding the element will resize the parent container or change the size of the element itself.

In essence, what I need is a tool that allows me to see into the future.

const byId = (id) => document.getElementById(id);
#container {
  height: 3em;
  min-width: 50%;
  background: teal;
 }

#mystery {
  background: purple;
}
<div id="container">
  <div id="mystery">Some Text</div>
</div>


<button onClick='byId("mystery").style.position = "relative"'>Position Relative</button>
<button onClick='byId("mystery").style.position = "absolute"'>Position Absolute</button>


Currently, these are the only solutions I can think of (and they're all quite ridiculous):

  1. Create a duplicate of the entire webpage HTML with opacity: 0; pointer-events: none, then render the future secretly on the clone.

  2. Capture the painting data of the current page (essentially taking a screenshot), overlay that while making secret modifications to the page to see the future result, then revert back and remove the overlay.

  3. Similar to number 2, is there a way to ❄️freeze❄️ rendering of a page for 3-4 frames?

  4. I vaguely remember hearing about something called a "sizing worker" a long time ago. I couldn't find any information on it now, but it might prove useful in this scenario?

Answer №1

If you want to customize the sizes of elements on your webpage, you can easily do so by manipulating the properties with JavaScript. By changing the property values temporarily and then reverting them back, you can achieve the desired effect without compromising speed. Have you experimented with this approach yet?


Asker Edit: Here is a sample code snippet that demonstrates how you can implement this functionality:

function byId(id){ return document.getElementById(id); }
const tweenyEl = byId("tweeny");

function appendTweeny() {
  tweenyEl.style.opacity = "1";
  const startingWidth = tweenyEl.clientWidth + "px"
  tweenyEl.style.position = "relative";
  const targetWidth = tweenyEl.clientWidth + "px";
  console.log(startingWidth, targetWidth);
  
  tweenyEl.style.width = startingWidth;
  requestAnimationFrame(() => 
    requestAnimationFrame(() =>
      tweenyEl.style.width = targetWidth
    )
  );
}

function resetTweeny() {
  tweenyEl.style.position = "";
  tweenyEl.style.width = "";
  tweenyEl.style.opacity = "0.1";
}
#container {
  display: inline-block;
  height: 3em;
  min-width: 150px;
  background: teal;
}

#tweeny {
  font-family: arial;
  color: white;
  position: absolute;
  background: purple;
  transition: all 0.5s ease;
  opacity: 0.1;
}
<div id="container">
  <div id="tweeny">I'm Tweeny</div>
</div>

<br>
<button onClick='appendTweeny()'>Append Tweeny</button>
<button onClick='resetTweeny()'>Reset Tweeny</button>

Answer №2

My recommendation would be to duplicate the page within an iframe and hide the iframe off the viewport.

<iframe style="width:100vw;height:100vh;left:-101vw;positionabsolute"><iframe>

Answer №3

It is important to consider that the user has the ability to zoom in and out freely! Each browser may interpret the same content differently, so determining the exact size of an element can be uncertain until it is actually rendered.

There is uncertainty about whether specifying display: none; will prompt the browser to calculate measurements for elements that are not visible.

Answer №4

By replicating an element in real-time with the same transformation and a delay of 0, you can determine its width and height before making any adjustments to your current animating element.

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

Creating a unique AngularJS custom directive that utilizes ng-options can be achieved by populating

I've encountered a major roadblock in my project, and despite my efforts to troubleshoot, I can't seem to find the solution. The issue revolves around populating options within an ng-options directive through a service. This directive is nested i ...

Attempting to insert an empty <option> into a dropdown menu using jQuery and ajax functionality

I'm working on a JavaScript function that dynamically populates a select dropdown based on the value of another select dropdown. I want to include an empty option at the beginning. Here is the code snippet for the function: function createParkFloorM ...

iOS app launch does not trigger Phonegap handleOpenURL

Receiving an alert message when the app is open in the background. However, when I close the app from the background and then relaunch it, the alert message doesn't appear. The handleOpenURL function cannot be invoked in JavaScript when the app is lau ...

"Execution of the console.log statement occurs following the completion of the request handling

When I have a piece of middleware that responds if no token is found, why does the console.log line still run after the request is responded to? I always believed that the res.json call would "end" the middleware. Any insights on this behavior would be g ...

What is the best way to link and store invoice formset with the main form foreign key in Django?

I am new to Django and need help. I am trying to save my invoice in a database, but the issue I'm facing is that I can't retrieve the foreign key from the main form when I try to save the formset. View.py def createInvoice(request):` if requ ...

saving data in an array using JavaScript

I have a requirement to store values into an array in HTML that are generated by a random number generator in Python as {{player.a1s1}}. I have successfully handled this part. Essentially, every time the button "mm1a" is clicked, a new button will be displ ...

ways to instantly showcase the input's value within a DIV element

For example, I have a div with the ID of "someDiv" and an input text field with the ID of "someInput". How can I make it so that the value entered into the input field displays in the DIV in real time? For instance, if I type the letter "a" in the input fi ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Receive a response in fragments from express on the browser

As I work on creating a progress bar to track long-running server-side tasks that may take up to a few minutes, I am exploring different methods to display the progress of each task. While WebSockets and interval polling are options, I prefer using long-po ...

Guide to making a Grid element interactive using the Link component

PostsList component is responsible for rendering a list of posts. The goal is to enable users to click on a post item and be redirected to the specific post's link. const PostsListView = ({ posts, setError, isloggedin }) => { const [redirectCre ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...

Move the box upwards and change it to grayscale when hovering over the image, then reverse the effect when the hover

As I hover over the image, my goal is to make a gray box appear at the bottom and smoothly slide up. While it slides up, everything it covers should turn grayscale. When I move my mouse away from the image, I want the gray box to slide back down and remove ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Can we modify a currently active document within MongoDB?

Is there a more efficient way to achieve the same functionality in JavaScript? I have to find a user, validate their password, and then update their document. Can I optimize this process by reusing the already retrieved document (stored in var doc) for up ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

Utilizing YouTube API information with AngularJS

I am currently working on a project where I need to fetch all the playlists from a specific channel and then display the name of each playlist in my AngularJS application. var myApp = angular.module('app', ['ngResource']); myApp.facto ...

Utilizing an additional parameter in React to dynamically change the API URL

Hello everyone! I'm facing a slight issue with one of my React applications: I'm attempting to retrieve Weather alerts using an API. Here's how my App.js file is set up: import React, { Component } from 'react'; import './App ...