Utilizing Javascript for a seamless transition to collapse a div to a height of 0 pixels

Two radio buttons are in place, with one pre-selected upon loading the page. If 'yes' is checked, a div will have a height of 100%, while 'no' will set the height to 0px (making it invisible). Upon switching between the buttons, the div will slide up or down accordingly.

The functionality is smooth except when 'yes' is initially checked - the div correctly appears visible on load, but when 'no' is selected, it suddenly disappears instead of sliding smoothly. However, after interacting with the buttons again, it functions as expected.

This behavior has been replicated in a jsfiddle, where the effect can be observed (even though the text remains visible). On the first click of 'no', the div jumps rather than slides, but subsequent clicks work as intended.

This is the HTML structure:

<input id='editpositive' class='form__radio-input' type='radio' name='subgroupEdit' value='editpositive' checked=checked/>
     <label class='form__radio-label' for='editpositive'>
        <span class='form__radio-button'></span>Yes</label>
<input id='editnegative' class='form__radio-input' type='radio' name='subgroupEdit' value='editnegative'/>
    <label class='form__radio-label' for='editnegative'>
       <span class='form__radio-button'></span>No</label>
         <div class='subgroupEdit-accordion-show'>
           STUFF GOES HERE
         </div>

CSS styling:

.subgroupEdit-accordion-show {
    transition: height 0.5s ease-in-out;
    height: 100%;
 }

Javascript implementation:

const slideDown = element => element.style.height = `${element.scrollHeight}px`
const slideUp = element => element.style.height = `0px`
document.getElementById('editpositive').addEventListener('click', async () => {
    slideDown(document.querySelector('.subgroupEdit-accordion-show'))
})

document.getElementById('editnegative').addEventListener('click', async () => {
   slideUp(document.querySelector('.subgroupEdit-accordion-show'))
})

How do I achieve a smooth sliding animation to adjust the div height to 0px when it is initially visible on page load?

Answer №1

It's important to set a fixed height for this to function correctly on the initial attempt.

You can experiment with this CSS code:

.subgroupEdit-accordion-show {
  transition: height 0.5s ease-out;
  height: 15px;
}

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

ways to assign local file path as image url in json

Hey there, I am a new tool for angularjs. Take a look at the json file below: [ { "name": "WORLD", "population": 6916183000, "flagurl":"C:\xampp\htdocs\selva \Flag_of_the_People's_Republic_of_China.svg" }, { "na ...

FireFox appears to be experiencing issues with accessing the contentDocument of a frame using jQuery

While this line of code functions correctly on Chrome and IE, it encounters an issue on FireFox. The error message displayed in the FireFox console is: ReferenceError: $ is not defined var lang = $($('#navFrame')[0].contentDocument).find('# ...

Struggling to avoid displaying unauthorized content in next.js prior to navigation to a new route

import JoinComponent from '@/components/join/JoinComponent' import Footer from '@/components/Layouts/Footer' import GuestLayout from '@/components/Layouts/GuestLayout' import Navbar from '@/components/Layouts/Navbar' ...

What steps can be taken to troubleshoot this AngularJS code?

When errors occur within Angular, debugging becomes quite challenging for me. Here is the code snippet I am working with: <script> var my_app = angular.module("campaign_listing", ['$http']); var controllers = {}; controllers.ca ...

What is the best way to determine the nearest vertex to a given 3D point?

https://i.sstatic.net/Ooh8W.png Objective: I am aiming to identify the closest vertex to the clicked point. Components Needed: Perspective camera Icosahedron geometry (applied basicmeshmaterial with wireframe) Rotating geometry Raycaster Current Clic ...

Ways to eliminate line breaks in CSS

I'm currently working on a project and I'm facing an issue with text auto-entering without using any breaks. I'm not sure what the exact problem is. I implemented a code snippet from Overstack to display a div on hover. Perhaps the positioni ...

Should commas be used in variables?

Could this be converted in a different way? $('#id').testfunction({ 'source' : [ {'source':'pathimage.jpg','title':'Title 1','description':'This is a description 1.'}, ...

Creating a Scrollable React Form Group

Struggling to display a large amount of data that is not scrollable, how can I make this form group scrollable to easily view all the data? render() { return ( <div style={{width: '50rem', margin: '1rem&ap ...

Three divs are set in place, with two of them of fixed width while the third div is

Looking for a layout with specific positioning and fixed widths: One box on the left, one box on the right, each with a width of 200px. The middle div should adjust to take up the remaining space. Any suggestions are appreciated. Thank you! ...

I am disappointed with the lack of functionality in Angular's HTML type inference

When working inside an Angular component, I want to select a div element by id or class. This method works menuDisplayDiv = document.getElementsByClassName("some_class")[0] as HTMLDivElement; menuDisplayDiv = document.getElementById("some ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

CSS animations - Modifying a style element while maintaining the existing timing restrictions

I use CSS transitions to rotate an image img { transition:all 5s ease-out; } To change the rotation direction, I utilize jQuery $('img').css({'transform':'rotate('+2000+'deg)'}); Is it possible to switch the ...

Eliminating specific item from array

(2) [{…}, {…}] 0: {id: "201158", salary: 2} 1: {id: "1627761", salary: 5} length:2 __proto__: Array(0) Here is the object retrieved from the console, and I'm facing a challenge that needs some resolution. When a certain element is clicked, I in ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

How can I trigger $stateChangeStart in Angular ui-router when using state.go({notify:false})?

My Angular SPA uses ui-router for navigation and infinite scroll functionality. I currently implement infinite scroll by utilizing the following code snippet: $state.go('someStateWithPagination', {page: page+1}, {notify: false, reload: false}) ...

List of items lacking proper sorting functionality

I have encountered an issue while sorting an array of objects using a sorting function. It seems that the sorting function does not have any effect on the array, resulting in the same unsorted list. However, when I exported the array and the sorting funct ...

After the page has finished loading, the JavaScript code is not able to

I have created a dynamic jobs list from a database that includes conditional salary reporting based on union type. I decided to build the dataset in the page load section of the CS page for output to a label on the ASPX page to handle the conditional state ...

In the process of crafting a storyboard for a new graphic novel

For my latest project, I am working on creating a comic book page. After successfully designing a cover that opens up, I am now facing a challenge in adding separate blocks to the first page to resemble a classic comic book layout. However, every time I a ...

Align the image in the center of the Navigation List vertically

I'm working on creating a responsive navigation list with a centered image inside. I've almost got it, but the image appears higher up than the rest of the list. My goal is to achieve this layout, but I'm having trouble figuring it out: htt ...

Creating a customized image modal in ReactJS that incorporates a dynamic slideshow feature using the

I am attempting to incorporate an image lightbox into my React application: https://www.w3schools.com/howto/howto_js_lightbox.asp Here is the link to the CodeSandbox where I have tried implementing it: https://codesandbox.io/s/reactjs-practice-vbxwt ...