Obtain the height of an invisible element

I am faced with the challenge of determining the height of an element in order to smoothly transition it. The issue I encounter is that the element initially has no fixed height due to potential disruption of my website layout.

This height value varies depending on the device used to access the site and represents the height of my text box.

One approach could involve loading the page without hiding the text, obtaining its height, and then concealing it using JavaScript. However, I do not consider this a preferred solution.

Ultimately, my objective is to ensure that regardless of whether the page contains only images or displays text, everything is centered both vertically and horizontally.

document.getElementById("intro-img").onclick = function() {
  $("#intro-img").toggleClass('show');
  $("#text").toggleClass('show');
}
.full-size {
  height: 100vh;
  overflow: hidden;
}
.title-img {
  max-height: 250px;
}
#intro-img {
  cursor: pointer;
  height: 250px;
  transition: all 0.75s linear;
}
#intro-img.show {
  height: 125px;
}
#text {
  opacity: 0;
  height: 0;
  transition: all 0.75s linear;
  overflow: hidden;
}
#text.show {
  opacity: 1;
  height: 105px; /* I need this value set based on vw */
}
.container {
  margin-left: auto !important;
  margin-right: auto !important;
}
.row {
  width: 100%;
  margin-left: auto !important;
  margin-right: auto !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="container full-size valign-wrapper">
    <div class="row">
      <div class="col s12 center-align">
        <img id="intro-img" class="responsive-img title-img" src="http://undeadleech.com/img/UndeadLeech_x3_round.png">
      </div>
      <div id="text" class="col s12 center-align">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
      </div>
    </div>
  </div>
</body>

Answer №1

To determine the height of an element, you must first render it according to my knowledge. Here's a suggestion on how to achieve this:

  • Initially, render the page with your element appearing as if it had height by applying height: auto (disregarding the height: 0)
  • Retrieve the actual height of the element
  • Remove the temporarily added inline style, specifically height: auto
  • Create a special rule for this in a <style> tag

Note: Remember to update the style with the new height if you resize the page.

var $text = $('#text')
$text.css({ height: 'auto' })
var height = $text.css('height')
$text.css({ height: '' })

// JavaScript code snippet to dynamically create and apply CSS class
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '#text.show { height: ' + height + ' }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById("intro-img").onclick = function() {
  $("#intro-img").toggleClass('show');
  $("#text").toggleClass('show');
}
.full-size {
  height: 100vh;
  overflow: hidden;
}
.title-img {
  max-height: 250px;
}
#intro-img {
  cursor: pointer;
  height: 250px;
  transition: all 0.75s linear;
}
#intro-img.show {
  height: 125px;
}
#text {
  opacity: 0;
  height: 0;
  transition: all 0.75s linear;
  overflow: hidden;
}
#text.show {
  opacity: 1;
  /*height: 105px; /* I need this value set based on vw */
}
.container {
  margin-left: auto !important;
  margin-right: auto !important;
}
.row {
  width: 100%;
  margin-left: auto !important;
  margin-right: auto !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>

<body>
  <div class="container full-size valign-wrapper">
    <div class="row">
      <div class="col s12 center-align">
        <img id="intro-img" class="responsive-img title-img" src="http://undeadleech.com/img/UndeadLeech_x3_round.png">
      </div>
      <div id="text" class="col s12 center-align">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
        sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et
        ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
      </div>
    </div>
  </div>
</body>

Answer №2

If you want to determine the size, you'll need to render it, as mentioned by Mauricio Poppe. However, this can be done without actually displaying it on the screen. Simply set the opacity to 0 to make it invisible.

function calculateElementHeight(element) {
  element.classList.add("hidden");

  // Add it at the beginning
  if (document.body.childNodes[0]) {
    document.body.insertBefore(element, document.body.childNodes[0]);
  } else {
    document.body.appendChild(element);
  }
  
  var height = element.clientHeight;

  document.body.removeChild(element);
  element.classList.remove("hidden");

  return height;
}
.hidden {
  opacity: 0;
  z-index: -1000000000; /* Move to the back */
  display: block; /* Required for z-index */
  pointer-events: none;
}

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 compatibility between Typescript methods and event handlers is lacking

Consider this basic TypeScript script class foo { v: number = 1; public bar() { console.log(this.v); } } var a = new foo(); var b = new foo(); document.getElementById('test').addEventListener("click", a.bar); document.getE ...

Weapons of Mass Destruction - receive markdown content

My application is utilizing a markdown editor from Google Code. $(document).ready(function () { var converter = Markdown.getSanitizingConverter(); var editor = new Markdown.Editor(converter); editor.run(); }); <div class="wmd-panel"> ...

Styling a specific element in Svelte without needing a globally unique identifier

How can I target just the outer div using a css selector? <div> <div>...</div> <div>...</div> </div> <style> OUTER.DIV.ONLY { background: url(outer.png); } </style> Alternatively, I& ...

Initiate an asynchronous request from JavaScript to a C# controller located in a separate directory

Note: Updated at the bottom of question I'm encountering difficulties with making an AJAX call from JavaScript to the C# Controller. The issue seems to be related to the connection URL in my AJAX call within the JavaScript file. If the URL isn't ...

Issue with Firefox: During drag events, dataTransfer.files return as null, while this behavior is consistent in all other browsers

Take a look at this jsfiddle to see the exact issue in action. In my experience, the 'dragenter' event dataTransfer.files works correctly in all browsers except for Firefox. However, I have noticed that the 'drop' event consistently pr ...

Using Django to generate a JSON object from a model and pass it to a template

I am currently developing a Django-based Quiz application that will utilize Javascript for rendering. Each quiz in the system comprises multiple questions, each with a question text and various choices (some of which may be correct while others are incorre ...

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

"Adjusting the font size in a blogger's photo caption: A quick guide

I recently switched templates for my blog and I'm having trouble adjusting the size of the caption text under the photos. The template I'm currently using is called Awesome Inc. If you need more information, you can visit my blog here: https:// ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

What is the best way to navigate to the href link?

After attempting to use driver.find_element_by_id // link_text // partial link text without success, I'm wondering what method I should be using to access this href. Currently encountering a No Such Element Exception. Any assistance would be greatly a ...

Can CSS masking be implemented in all current web browsers?

Could this html element be replicated using only an image and CSS? Alternatively, could an SVG object or extra divs be utilized for the same effect? The goal is to ensure compatibility with all modern browsers, including IE/Edge. Any suggestions on achievi ...

Retrieve and store an array from a JSON response using jQuery

Appreciate the assistance in advance. I am currently working with a plugin that requires a JSON response to be formatted as an array instead of an object. Below is a snippet of the JSON response I am receiving: { "instruments": [ { ...

Transition the canvas video from black and white to full color

I am working with two elements - a video and a canvas. There is a function that draws the video on the canvas in grayscale when the video plays. I also have a button that is supposed to fade the canvas video from grayscale back to color. Currently, the cod ...

"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four. Currently, the chart animates upon loading. How can I make it so that when #chartTrig ...

Vertically center the button inside a MaterialUI grid

How can I vertically center align the button within this grid? I've tried using vertical-align but it doesn't seem to work. I'm currently adjusting the vertical position of the button using top: "30%", but I'm looking for a better way t ...

Deleting Cart Items Permanently with AJAX in Vue.js and Shopify

Seeking assistance with implementing a feature to remove a product from a MiniCart using Vue.js in a Shopify theme. Below is the code snippet for minicart.liquid file along with the cart data stored in the 'data' property. Although the remove fun ...

Button click not clearing the contents of the div container

I am currently working on a JavaScript, HTML, CSS, and Bootstrap project for a tennis club. The project includes a login page (index.html) and a manage player page. Within the manage player page, there are two buttons - add players and show players. When t ...

javascript The onclick function works only for a single interaction

Every time I click on the Button, the first click triggers func1 successfully. However, subsequent clicks fail to execute the function. Even the alert('func1') statement is not being displayed. What mistake am I making here? func ...

The CSS background shadow on one div behaves differently compared to the neighboring div

Currently, I am facing an issue where I have two divs positioned next to each other in a line. http://jsfiddle.net/A5Jc7/60/ The HTML structure is as follows: <div> <div class="box1"></div> <div class="box2"></div> ...