What is the best way to incorporate a CSS transition without any dynamic property changes?

Is there a way to add a transition effect to a header when its size changes without a specified height value in the CSS? The header consists of only text with top and bottom padding, so as the text changes, the height adjusts accordingly. How can I implement a smooth transition in this scenario? Let me illustrate my query with some code:

$(document).ready(function() {
    $('.header').click(function() {
      if ($('.header').html() == 'Hello World (Click this header)') {
          $('.header').html('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent dapibus. Nullam eget nisl. Nunc auctor. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Praesent vitae arcu tempor neque lacinia pretium. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ac dolor sit amet purus malesuada congue. Pellentesque arcu.');
      } else {
          $('.header').html('Hello World (Click this header)');
      }
  });
});
    
.header {
  color: #fff;
  font-family: helvetica;
  position: fixed;
  right: 0px;
  left: 0px;
  top: 0px;
  padding: 30px 15px;
  background-color: #4d5366;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  user-select: none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="header">Hello World (Click this header)</nav>

Answer №1

One solution could be to adjust the bottom value in order to control the height:

$(document).ready(function() {
  $('.header').css('bottom', 'calc(100vh - ' + $('.header div').css('height') + ' - 60px)')
  $('.header').click(function() {
    if ($('.header div').html() == 'Hello World (Click this header)') {
      $('.header div').html('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent dapibus. Nullam eget nisl. Nunc auctor. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Praesent vitae arcu tempor neque lacinia pretium. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ac dolor sit amet purus malesuada congue. Pellentesque arcu.');
    } else {
      $('.header div').html('Hello World (Click this header)');
    }
    $('.header').css('bottom', 'calc(100vh - ' + $('.header div').css('height') + ' - 60px)')
  });
});
.header {
  color: #fff;
  font-family: helvetica;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  padding: 30px 15px;
  box-sizing: border-box;
  background-color: #4d5366;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="header">
  <div>Hello World (Click this header)</div>
</nav>

Answer №2

If you're looking to adjust the height of the .header element, start by setting it to auto. When its content changes, retrieve the height of .header with jQuery using

var headerHeight = $('.header').outerHeight();
, and then set the height of .header to this value instead of auto by using
$('.header').css({'height': headerHeight})
. Remember to reset the height to auto each time new content is added in order to accurately capture the updated height of the .header div.

Additionally, consider adding a transition effect to .header like so:

transition: height 0.25s ease-in-out;
. Feel free to reach out if you need further assistance or clarification on your original query. :)

Answer №3

When swapping text, it happens instantly without waiting for the screen to refresh. If you don't specifically set the height of an element in the inline or stylesheet, the element won't resize when the text is swapped.

To work around this issue, you can measure the dimensions of your header with both long and short text snippets, save those values, and then explicitly set the height of the element when the text swap occurs based on each state.

Here's a simple explanation using vanilla JavaScript...

<!-- HTML -->
<div id="header" class="offpage">Hello World!</div>

/*** CSS ***/
#header {
    position: fixed;
    right: 0; left: 0; top: 0;
    height:auto;

    color: #fff;
    background-color: #4d5366;

    font-family: helvetica;
    font-size:1rem;
    line-height:1.6;

    padding: 2rem 1rem;

    cursor: pointer;
    transition: all 0.3s ease-in-out;
    user-select: none;
    overflow: hidden;
}
#header.offpage {
    top: -110%;
}

/*** JS ***/
var text = {
    longText: "Lorem ipsum dolor sit amet...",
    shortText: "Hello World!"
};

var header;

function setHeaderDimensions() {
    /* Get the height of default text 
       and store it in an inline data-* attribute */
    var headerHeight = header.clientHeight
    header.setAttribute("data-dims-shortText", headerHeight);

    /* Swap text and get the height of longText */
    header.textContent = text.longText;
    header.setAttribute("data-dims-longText", header.clientHeight);

    /* Reset default text */
    header.textContent = text.shortText;

    /* Define explicit height for the default state */
    header.style.height = headerHeight + "px";

    /* Display on the page */
    header.classList.remove("offpage");
}

function changeHeaderText(e) {
    /* Check the current state */
    var flag = header.classList.contains("long");

    /* Set text accordingly */
    header.textContent = text[flag ? "shortText" : "longText"];

    /* Get the required stored height */
    header.style.height = header.getAttribute(
        flag ? "data-dims-shortText" : "data-dims-longText"
    ) + "px";

    /* Toggle state */
    header.classList.toggle("long");

}

function onPageLoaded() {
    header = document.getElementById("header");

    /* Get and set #header dimensions
       for each text-state (long & short) */
    setHeaderDimensions();

    /* Add event handler */
    header.addEventListener("click", changeHeaderText, !1);
}

document.addEventListener("DOMContentLoaded", onPageLoaded, !1);

That's the concept. Hopefully, you can use this as a starting point and customize it further. :D

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

Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element. I am encountering two issues... Despite setting initial values in Formik, the TextFiel ...

Flashing tilemap during the update process

I'm attempting to create a game map on a canvas using a JSON file produced by tiled map editor. I believe I am close to accomplishing this, but I encounter one issue. When I include the call to load the map in my update function, the map flickers on ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

"Excessive use of Javascript setInterval combined with frequent ajax calls is causing significant

I have integrated the setInterval() function into my JavaScript code to make an AJAX call every 2 minutes. However, I noticed that this is causing the website to slow down over time. The website is built using Node.js. After doing some research, I came acr ...

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

Managing errors in React Router on the server-side

I am currently working on an isomorphic application using react-router and express. My goal is to implement custom error pages that will be displayed in case of server-side errors, rendering errors, or when a page is not found. However, I am facing difficu ...

activate a CSS-only modal with JavaScript

Is it possible to trigger a pure CSS modal using JavaScript (jQuery) without the need for a label, so that it activates when a user visits a page? http://jsfiddle.net/h84nubzt/ <label class="btn" for="modal-one">Example</a> <!-- Modal ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

Display Button Information in InfoPath Form

In InfoPath 2010, I created a form and published it to a SharePoint 2010 list. The end user wants to print this form for their records, but when using the web part to print the screen, the page comes out very small and unusable. Is there any HTML code th ...

Following the same occurrence using varying mouse clicks

I am currently exploring the most effective method for tracking file downloads (specifically, pdf files) on my website using Google Analytics (UA). I understand that by utilizing <a href="book.pdf" onClick="ga('send','event','P ...

Is it possible to load a webpage in a WebBrowser control without displaying certain HTML elements by their IDs

Is there a way to load a specific page using the WebBrowser control without displaying unwanted advertisement banners in the 'tb' DIV element? I've searched online and came across an example that uses the mshtml reference, but I can't ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

The jQuery UI accordion fails to function properly after refreshing the data

I am facing an issue with my HTML page where data is loaded dynamically into accordions. The accordion functionality is implemented inside a function, which is called at regular intervals to refresh the data. Initially, the accordion displays correctly, bu ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Textbox value disappears after being updated

When I click on the edit link (name), the value from the database is displayed as a textbox. However, when I update another normal textbox (age), the value in the edit link textbox disappears. Strangely, if I input a new value into the edit link textbox, i ...