What is the best way to determine the actual height of a DOM element that is being hidden by the overflow property in order to create a seamless CSS transition to height: auto

Solution:

Thanks to @Kalimah, here's a solution that works in

composition api & script setup
:

<script setup>
const state = reactive({
    meetCardHeight: 100
})

const element = ref(null)

const changeElementHeight = () => {
    if (state.meetCardHeight !== element.value.scrollHeight) {
        state.meetCardHeight = element.value.scrollHeight
    } else {
        state.meetCardHeight = 100
    }
}
</script>

<template>
  <div ref="element" class="w-6/12 p-4 mx-auto rounded border border-slate-400 bg-slate-50 shadow cursor-pointer hover:border-slate-600 hover:shadow-md transition mb-4 overflow-hidden transition-all duration-500" :style="{ height: state.meetCardHeight + 'px'}" @click="changeElementHeight">

    <h1>Hello World</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto at atque beatae commodi cumque delectus dolor doloremque enim est et eum ex facere id illum incidunt, ipsum iusto labore laboriosam libero magnam minima molestias nobis nulla officia perspiciatis placeat porro possimus quo sequi tempore tenetur velit voluptatibus? Adipisci amet asperiores, autem explicabo fuga fugiat, id illum nobis obcaecati quam quasi, quibusdam tempora voluptatem? Adipisci aliquam at dignissimos dolore doloribus eaque itaque minus nam possimus quae quia temporibus vel, vero!</p>

  </div>
</template>

This code will make the div expand to its full size with a smooth transition effect.

Original Question:

I'm trying to calculate the actual height of all text within this component, even though some parts are hidden due to overflow: hidden (using tailwind):

<script setup>

const state = reactive({
    meetCardHeight: 100
})

</script>

<template>
  <div ref="element" class="w-6/12 p-4 mx-auto rounded border border-slate-400 bg-slate-50 shadow cursor-pointer hover:border-slate-600 hover:shadow-md transition mb-4 overflow-hidden transition-all duration-500" :style="{ height: state.meetCardHeight + 'px'}">

    <h1>Hello World</h1>
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto at atque beatae commodi cumque delectus dolor doloremque enim est et eum ex facere id illum incidunt, ipsum iusto labore laboriosam libero magnam minima molestias nobis nulla officia perspiciatis placeat porro possimus quo sequi tempore tenetur velit voluptatibus? Adipisci amet asperiores, autem explicabo fuga fugiat, id illum nobis obcaecati quam quasi, quibusdam tempora voluptatem? Adipisci aliquam at dignissimos dolore doloribus eaque itaque minus nam possimus quae quia temporibus vel, vero!</p>

  </div>
</template>

The current height of the component is set to 100px to enable the overflow functionality. Is there a way to determine the total height that the h1 and p tags would occupy if there was no overflow constraint?

Answer №1

To determine the height, you can utilize the scrollHeight property. This is a JavaScript native property and operates independently of vue or any other libraries.

For example:

console.log("Full Height", document.querySelector(".container").scrollHeight + "px");
.container{
height: 100px;
overflow: hidden;
}
<div class="container">

    <h1>Hello World</h1>
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto at atque beatae commodi cumque delectus dolor doloremque enim est et eum ex facere id illum incidunt, ipsum iusto labore laboriosam libero magnam minima molestias nobis nulla officia perspiciatis placeat porro possimus quo sequi tempore tenetur velit voluptatibus? Adipisci amet asperiores, autem explicabo fuga fugiat, id illum nobis obcaecati quam quasi, quibusdam tempora voluptatem? Adipisci aliquam at dignissimos dolore doloribus eaque itaque minus nam possimus quae quia temporibus vel, vero!
    
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto at atque beatae commodi cumque delectus dolor doloremque enim est et eum ex facere id illum incidunt, ipsum iusto labore laboriosam libero magnam minima molestias nobis nulla officia perspiciatis placeat porro possimus quo sequi tempore tenetur velit voluptatibus? Adipisci amet asperiores, autem explicabo fuga fugiat, id illum nobis obcaecati quam quasi, quibusdam tempora voluptatem? Adipisci aliquam at dignissimos dolore doloribus eaque itaque minus nam possimus quae quia temporibus vel, vero!
    
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto at atque beatae commodi cumque delectus dolor doloremque enim est et eum ex facere id illum incidunt, ipsum iusto labore laboriosam libero magnam minima molestias nobis nulla officia perspiciatis placeat porro possimus quo sequi tempore tenetur velit voluptatibus? Adipisci amet asperiores, autem explicabo fuga fugiat, id illum nobis obcaecati quam quasi, quibusdam tempora voluptatem? Adipisci aliquam at dignissimos dolore doloribus eaque itaque minus nam possimus quae quia temporibus vel, vero!</p>

  </div>

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

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

What is the method to restrict the coverage of the background color within a specific region in HTML?

I am still fairly new to html so I apologize if this is a very basic question for you. Here is the css file that is causing me trouble: .sidepanel-list{ margin-left: 10px; background-color:lightgray; Whenever I run the code, the background color s ...

Attempting to create a hexagon using 127 divisions results in a gap

I am faced with a challenge of arranging 127 divs to form a hexagon shape similar to the example below: for (i = 1; i <= 127; i++) { var div = document.createElement('div'); document.getElementsByTagName('body')[0].appendChild( ...

If the duration is 24 hours, Moment.js will display 2 days

Looking for a way to allow users to input specific timeframes? For example, 1 week or 5 days and 12 hours. I found that using Duration from Moment.js seemed like the best solution. The snippet of code below is currently giving me 2 00:00, indicating 2 day ...

The left-floating elements are only partially functional

I recently encountered an issue with my HTML page that features a basic image gallery enhanced by lightboxes (fancybox). The images are meant to align left, with the first row containing three images and the second row containing two. <div class="image ...

Passing PHP data to a JavaScript file using JSON格式

I have a query regarding how to pass php variables and send their values to a js file using json. Here is what I currently have: <?php $data = array('artist' => $artistname, 'title' => $songname); echo json_encode($data); // ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...

Exiting the Protractor timeout setting for Safari WebDriver

While I have experience with unit tests using Karma, my office is now interested in integration tests, specifically to test cross-browser capabilities. Protractor seemed like the best option for this, so I began working on some basic dashboard tests. Howev ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Is it possible to divide a text string into distinct arrays using spaces?

One method I am familiar with for splitting a string involves using the .split() method, like so: function split(txt) { return txt.split(' '); } When executed, this function would return ['hello', 'world'] if provided wi ...

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Is there a delay following the click on the file upload button?

Whenever I attempt to choose a file for upload by clicking on "Select File" (input type=file), there seems to be a lag between the moment I click the button and when the selected file appears next to the button. It almost seems as if the browser is attempt ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

Retrieve data from a JSON file using Ajax and jQuery

I have a JSon file that contains information about some matches: [{ "id": "2719986", "orario": "00:30", "casa": "Bahia", "trasferta": "Internacional" } , { "id": "2719991", "orario": "02:00", "casa": "Palmeiras", "trasferta": "Botafogo RJ" }] I'v ...

Collect information from forms and save it to a mobile phone number

Is it possible to forward form field details to a cell phone number via text message? Here is the code I currently have for sending form data to an email address. If any adjustments need to be made, please provide instructions. <?php if(isset($_POST[ ...

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

Using CSS transitions to animate elements with specified opacity values

My goal is to transition buttons from opacity 0 to opacity 1 with a delay, but I am facing an issue. Some of these buttons have the "selected" class which gives them an opacity of 0.35. However, when the transition starts, the buttons with the "selected" c ...

adjusting the size of the sidebar at the top to ensure that it does not overlap the top menu

I have a sidebar on my page that opens vertically when I click a button. The sidebar covers the company logo and name, so I want to make it smaller. Here is the code for the sidebar: <body> <nav class="navbar navbar-dark bg-dark" ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...