Steps to animate a div expanding to fit its content dimensions

I'm looking for a way to animate the opening of a div so that it adjusts to the size of its content. The content is fetched from a separate search using .load, which means it could be just a single line (no result) or multiple results that vary in height. I've read through numerous posts and tried different approaches, but haven't had any success so far.

My latest approach involves starting the animation with a small initial height so that it looks like the div is opening, then setting the height to auto so it expands to the final size. However, this method only animates the first part and doesn't adjust the height as intended. Here's an excerpt from my document ready function:

$( "#TwoSearch" ).click(function() {
    $("#div1").animate({ height:0 }, 500).empty(); <!--- close div 1 --->
    $("#div2").animate({ height:200 }, 500);
    SW=document.getElementById("SearchWords").value;
    $("#div2").load("TwoSearchExercise.cfm?SW=" + encodeURI(SW), function () {
        $('.js-lazyYT').lazyYT(); 
        $("#div2").css('height','auto');
        });
    }); 

Is there a more elegant solution to achieve this effect? I've attempted to retrieve the height from inside the div, but it doesn't seem to work.

PS: This is a ColdFusion app, so please disregard the ## notation.

Answer №1

Your JavaScript code contains a couple of errors that need to be addressed: firstly, avoid using double ## as a selector as this can create confusion. secondly, having an HTML comment in your JavaScript code will result in a JavaScript error. In HTML files, comments are written like this: , while in JavaScript files, you should use // for single line comments and /* comment */ for multiline comments.

I had to make some adjustments to your code by commenting out the ajax part since I don't have a webserver available. Instead, I simulated it with a 1-second timeout. Here is the corrected code:

$( "#TwoSearch" ).click(function() {
    $("#div2").slideUp("fast");
    $("#div1").animate({ height:0 }, 500).empty();
    $("#div2").animate({ height:200 }, 500).empty();
    SW=document.getElementById("SearchWords").value;
    window.setTimeout(function() {
        var string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. The quick brown fox jumps over the lazy dog. "
        var loops = Math.floor(Math.random() * 50);
        var finalstring = "";
        for (var i = 0; i < loops; i++) {
            finalstring+=string;
        }
        $("#div2").text(finalstring);
        $("#div2").slideDown("slow");
    }, 1000);
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="TwoSearch">TwoSearch</button>
<input type="text" id="SearchWords" >
<div id="div1">
    
</div>

<div id="div2">
    
</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

Header, footer, and sidebars are all locked in place, while the central content area is designed for

Using this Demo Template as a starting point, I am looking to create a new layout: However, I am encountering the following challenges: The two sidebars are not properly contained within the scrollable content div. The content div does not have a fixed ...

Utilizing a Json.Net object within an Ajax request

Is there a way to pass a .Net object in an Ajax call using the Json.Net javascript library instead of json2.js? You can find more information on passing complex types via Ajax calls at this link: I am familiar with how to serialize and deserialize object ...

CSS Trick: How to Clear Content in a 3-Column Div arrangement

I've been struggling to clear the content below my three div columns, each consisting of a span with centered text and a textarea. It seems that the issue arises from the floating div tags without proper clearing. When viewed in Firefox, the next ele ...

What is the best way to sort through the data retrieved using jQuery.ajax()?

When utilizing the jQuery.ajax() method, I'm facing challenges in filtering the returned data to extract exactly what I need. Although it's straightforward with .load() and other jQuery AJAX methods, I specifically require using .ajax(). For ins ...

Jquery code is not functioning on elements that were not present during the initial page load

My web application includes javascript that is loaded on page load: $(function() { $('.modal-delete').click(function() { alert(); }); }); On my html page, I have a set of buttons that trigger blank message boxes when clicked: <butto ...

Customize the background color of Material UI input components on standard labels

Currently using react material ui and interested in changing the background color of a standard input. The issue arises when the label is overridden by the background color when the input is not selected. Input selected Input not selected This is my att ...

JSFiddle showcasing the Bootstrap grid system

I'm having trouble implementing bootstrap's grid system on jsfiddle. Check it out on jsfiddle I've tried using the example from the bootstrap documentation: <div class="row"> <div class="col-md-1">.col-md-1</div> ...

What is the best way to display grouped items horizontally in an ASP.NET ListView?

My ASP ListView currently displays items vertically in columns with GroupItemCount set to 3: A D G B E H C F I Is there a way to adjust the display so that it groups items horizontally in rows like this? A B C D E F G H I This is the ListVi ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...

How can I fetch a value from a database and set it as the selected option in a

I am facing an issue with the usage of the selectpicker plugin from Bootstrap in order to select multiple items. My requirement is to create a modal for editing where the data is fetched from previous records, particularly an array. I am looking for a way ...

Selection of multiple listings

Looking for a solution to create a multi list selection area? You can double click on an item in the left list to add it to the selected area. Also, you can double click on an item in the selected area to remove it from the list. <ul id="selection"> ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

The table is not properly displaying within the parent scrolled div due to issues with the fixed positioning

Apologies for any language barrier. I am encountering an issue with a PHP page that includes a table meant to be displayed as position:fixed; however, it consistently appears above the scrollbars and does not stay within the parent div. View screenshot he ...

Is there a way to implement an onclick event for every iframe within a document using jquery?

I have a webpage containing two iframes that can be switched using a selector. My goal is to implement an onclick event that will trigger a URL for specific <rect> elements within the iframes. After reading a helpful post on accessing iframe childr ...

I am looking to implement a feature in my quiz application where a green tick mark appears next to the question number for the correct answer and a red cross mark for the wrong answer

My HTML code here retrieves questions from a database and displays them based on the question number. <h4>{{indexOfelement+1}}</h4>&nbsp;&nbsp; In my CSS, I need to style the questions as follows: How can I achieve this? Each question ...

Conceal mobile button

Welcome to my website: Is there a way to hide the button on mobile phones? I want to create different buttons specifically for mobile devices. Below is the HTML code for the buttons. HTML <a href="http://site9171756.91.webydo.com/Info.html" target="p ...

Adjust the width of the table's td elements

I am looking to create a table similar to the one shown above. Here is my implementation. Please review my JSFiddle. HTML: <table border="0" id="cssTable"> <tr> <td>eredgb</td> <td><a href="self">0 ...

Left align the CSS menu text next to the menu image

Currently, I have a basic CSS menu that includes background images aligned to the left. My goal is to have the text float to the left of each image as well. <div class='mmenu'><ul><li><a id="li6" class="menu-news" href= "vie ...

Firefox compatibility issue: Bootstrap modal button not functioning properly when wrapping other HTML elements

Hey everyone, I've come up with some awesome image hover effects that you can use. I've implemented bootstrap modals so that when you click on 'show code', a pop-up will display with the HTML and CSS codes for easy copy-pasting. However ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...