Expand and Collapse div using JavaScript

Expand and Collapse div using JavaScript
Code Snippet:Toggle content
Author: T.J. Fogarty
Published: January 12, 2024
Last Updated: January 22, 2024
Downloads: 672
License: MIT
Edit Code online: View on CodePen
Read More

This simple JavaScript snippet helps you to expand and collapse div element on a webpage. It calculates and animates the height of the content div, providing a smooth visual transition.

Whether you are working on the accordion project or want to create multiple expandable/collapsible sections, this code quite fits your needs. With the help of this script, you can create interactive and space-efficient content displays on your website.

How to Expand and Collapse Div Using JavaScript

1. First of all, load the Normalize CSS and prefixfree JS by adding the following CDN links into the head tag of your HTML document. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

2. Create the HTML structure for expandable div elements as follows:

<ul>
  <li>
    <a href="#" class="expand">click</a>
    <div class="content">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat accusamus sequi eum commodi sint consequatur magni magnam non culpa laborum aperiam voluptatem velit dolore cupiditate tempore. Quibusdam unde voluptas eveniet. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem laudantium laboriosam distinctio numquam corrupti eius eum inventore voluptas. Saepe temporibus nemo nobis deserunt ipsa id at mollitia magnam iusto eos?</p>  
    </div>
  </li>
  
    <li>
    <a href="#" class="expand">click</a>
    <div class="content">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat accu</p>  
    </div>
  </li>
</ul>

3. Now, include the necessary CSS to style your expandable sections. The following code includes basic styling for the main container, content div, and the link. Customize the div element according to your needs.

.content {
  width: 0;
  height: 0;
  overflow: hidden;
  transition: height ease 0.5s;
}

.is-visible + .content {
  width: auto;
}

ul {
  list-style: none;
}
ul a {
  text-transform: uppercase;
  text-decoration: none;
}

4. The JavaScript code handles the expansion and collapse functionality. Copy the following code and include it in your HTML file, preferably at the end of the <body> tag.

var expand = document.querySelectorAll( '.expand' ),
    expandCount = expand.length,
    content = null,
    parent = null,
    parentWidth = 0;

for (var i = 0; i < expandCount; i++) {
  expand[i].onclick = function(e) {
    e.preventDefault();
    
    parent = this.parentNode;
    parentWidth = parent.offsetWidth;

    content = parent.querySelectorAll( '.content' )[0];
    
    // Calculate width of element to animate height
    var newHeight = getHeight( content, parent );
   
    content.style.height = newHeight + "px";
    
    if( !hasClass(this, 'is-visible') ) {
      addClass( this, 'is-visible' );
    } else {
      removeClass( this, 'is-visible' );
      content.style.height = "0px";
    }
  };
} 

function removeClass(elem, className) {
    var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
            newClass = newClass.replace(' ' + className + ' ', ' ');
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    }
}

function addClass(elem, className) {
    if (!hasClass(elem, className)) {
        elem.className += ' ' + className;
    }
}

function hasClass(elem, className) {
    return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}

function getHeight( el, parent ) {
  var newEl = document.createElement('p'),
      height = 0;
  newEl.innerHTML = el.innerHTML;
  newEl.setAttribute('id', 'test-height');
  
  parent.appendChild( newEl );
  
  height = document.getElementById( 'test-height' ).offsetHeight;
  
  parent.removeChild( document.getElementById('test-height') );
  return height;
}

That’s all! hopefully, you have successfully created an expandable div element on your website. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X