Increase the height of an element based on the content of the text within

Today I am facing a challenge: I need the text below to change when I click on one of these icons: https://i.sstatic.net/28xEF.png Luckily, it works with the following code:

CSS

.games-text {
    background-color: $color-primary;

    & p {
        max-width: 90rem;
        text-align: center;
        margin: 0 auto;
        padding: 3rem 0;
        font-size: 1.7rem;
        color: #D88087;
    }
}

JS

$(document).ready(function () {
    $('.games__game svg').click(function(e) {
        $('.games__game.active').removeClass('active');
        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

$(document).ready(function(){
    $("#game1 svg").click(function(){  
       $('.games-text').html('<p>Cash games, also sometimes referred to as ring games or live action games, are poker games played with "real" chips and money at stake, often with no predetermined end time, with players able to enter and leave as they see fit. In contrast, a poker tournament is played with tournament chips worth nothing outside the tournament, with a definite end condition (usually, only one player left), and a specific roster of competitors.</p>');
   });
});

$(document).ready(function(){
    $("#game2 svg").click(function(){  
       $('.games-text').html('<p>In a standard tournament format all players enter for the same amount of money which also carries a fee which the entity running the tournament keeps. As an example, “Casino Pokerology” might offer a no limit hold’em tournament that has a $50 entry cost plus a $5 fee to play. Once you post the $55, $50 of which goes into the prize pool and the other $5 is the fee to run the tournament, you may get $2,000 in non negotiable tournament chips. The blinds might start at $10 and $20 and escalate every twenty minutes. The continual escalation of the blinds forces the players to “gamble” more versus just playing conservatively and waiting for premium cards. This format is how the attrition of players whittles the number of starting players down to the eventual winners.</p>');
   });
});

$(document).ready(function(){
    $("#game3 svg").click(function(){  
       $('.games-text').html('<p>This type of tournament was started by the online poker sites but has now spread into the bricks and mortar cardrooms. They are played both one table as well as multiple tables. The name comes from the fact that to sign up all you need do is sit down. When the players in the tournament have all sat down – it “goes”. As an example, you enter an online poker site and select a one table sit & go (SnG), pay your entry fee, sit down and wait. The tournament starts when the last player who will complete the table sits down. These type of tournaments on the internet have become extremely popular, so much so that sometimes you need to be very “quick to click” in order to get in before the table fills up. One table sit & goes normally pay the top three finishers.</p>');
   });
});

$(document).ready(function(){
    $("#game4 svg").click(function(){  
       $('.games-text').html('<p>SPINS are three-handed Sit & Go tournaments where a multiplier between 2 and 240,000 randomly determines the size of the prizepool before the first card is dealt, so you could turn a $5 buy-in into a massive top prize of $1M in our SPINS $1M game.</p>');
   });
});

The issue here is that the height of the red container below depends on the text length. When there is more text, the height increases instantly. While this is acceptable, I would like to animate this height change somehow, yet I am unsure how to accomplish that. Can anyone provide assistance?

Answer №1

Implemented a wrapper div to enable height animation. Utilized .scrollHeight to calculate the height for the wrapper div and applied css transition: height 2s to animate the height.

$(document).ready(function() {
  $('.games__game svg').click(function(e) {
    $('.games__game.active').removeClass('active');
    var $parent = $(this).parent();
    $parent.addClass('active');
    e.preventDefault();
  });
});


$(document).ready(function() {
    // Game 1 functionality
});

$(document).ready(function() {
    // Game 2 functionality
});

$(document).ready(function() {
    // Game 3 functionality
});

$(document).ready(function() {
    // Game 4 functionality
});


$(document).ready(() => {
  var animHeight = () => {
    $('.gtwrap').css({
      overflow: 'hidden',
      height: $('.games-text').prop('scrollHeight'),
      transition: 'height 2s'
    })
  }
  animHeight();
  $('svg').click(() => {
    animHeight();
  })
});
.gtwrap {
  background-color: lightgrey;
}

.games-text p {
  max-width: 90rem;
  text-align: center;
  margin: 0 auto;
  padding: 3rem 0;
  font-size: 1.7rem;
  color: #D88087;
}

.games__game {
  display: flex;
  flex-direction: row
}

.games__game div {
  padding: 1px
}

svg {
  background-color: red;
  width: 30px;
  height: 30px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="games__game">
  <div id="game1"><svg></svg></div>
  <div id="game2"><svg></svg></div>
  <div id="game3"><svg></svg></div>
  <div id="game4"><svg></svg></div>
</div>
<div class="gtwrap">
  <div class="games-text">text</div>
</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

Storing an array in a cookie using Angular 8

Currently, I am utilizing the ngx-cookie-service package. { "user": [ { "id": 109, "name": "name1", "job" : "job name" } ], "token":"xxxx" } this.cookieService.set( 'user_id', ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

What's the best way to ensure that your item list automatically updates the rendered list when an item is deleted

I've developed a web cart using Redux. The cart functions as expected, except for one issue - when I delete an item from the cart, the changes are only displayed after refreshing or navigating to another page. How can I update the view dynamically as ...

Creating dynamic routes in express to enable flexible and customizable paths

Exploring the dynamic usage of paths in Express has been on my mind. Specifically, I have been employing lodash to locate a path in a separate file using regex methods. routes.js const json = require('./routes.json') const _ = require('l ...

Unsupported MIME format

I'm encountering an issue where my stylesheet is not applying to my handlebars. It was working fine yesterday, but today I'm seeing a MIME error and I'm unsure of the reason behind it. Any assistance would be greatly appreciated. Server Cod ...

Can you tell me which specific font Adobe Edge Code (Brackets) uses in its code editor?

Can someone please help me? I'm trying to identify the syntax highlighter being used in this code. Is it Prettify or something else? ...

Smoothly rotating an object in Three.js with a custom function

I successfully created a Rubik's Cube using Three.js, and everything is functioning as intended. However, I would like to add an animation when turning the cube instead of it snapping into place instantly. How can I achieve a smoother turning effect? ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

How can I implement custom code to run in all Ajax requests in Ext JS without having to manually insert it into each individual request?

When a user is logged in, ajax requests function properly. However, if the session becomes invalidated, the ajax returns a login screen and displays it as ajax content. I am wondering if it is feasible to incorporate custom code in Ext JS that would be e ...

Abort an ajax request if it is taking too long to finish

On my website, I have implemented a search feature that queries my database using Ajax and displays the results in a modal box upon successful completion. The modal is then shown once the results are loaded. My backend is powered by Django. Is there a me ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

What is the best way to center align and add an icon to the header in Ionic?

How can I center align an "ion-ios-arrow-up" icon in the header of my Ionic app, similar to the concept shown below? This is my HTML template: <ion-view cache-view="false" view-title="Historical HPP"> <ion-nav-bar class="nav-title-slide-ios7 ...

What is the proper way to incorporate a hashtag (#) into a PHP parameter within a URL

Currently, I am sending a PHP request to a login handler using the following URL: https://example.com/test.php?username=test123&password=hiuhsda3#24 However, I need to retain the hashtag in either the password or username along with anything that come ...

Adjusting Picture Sizes to Fit the Dimensions of a Photo Frame

Currently, I am in the process of developing a website that incorporates two distinct image types: Portrait photos Landscape photos As you can see, there are two different categories of images: Square Rectangular I need to resize all the phot ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Display information in an HTML table using JQuery AJAX and JSON data

As a new member and beginner learner, I have encountered some issues while trying to execute a certain task. Despite looking at similar questions, I couldn't find a solution that worked for me. What I am attempting to do is query my database to retrie ...

Bring in a JavaScript file from Blogger without using a tag

Is there a way to retrieve blogger feeds code without using <script src=? I attempted to achieve this using document.write, but it resulted in the deletion of the original page content upon import. Is there an alternate method to import when triggering ...

What is the best approach to retain a user's selection for dark mode?

I have created a small website to showcase my work, but I'm struggling to figure out how to make the website remember a user's choice of dark mode. After searching on Stack Overflow, I came across suggestions like using cookies or localStorage. ...

Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, wit ...