DEV Community

andysaktia
andysaktia

Posted on • Edited on

3 2

Collapse Bootstrap with History :)

One day I was working on a web project, with the collapse feature of bootstrap, I use this feature for product facets/category content. Since there were many collapses, five to be precise, there was a problem I encountered and this is the purpose of this script to work.

Alt Text

Purpose

Create a collapse hide/show based on the previous treatment.

Prerequire

  • Bootstrap class collapse; aria-expanded for status collapse and data-bs-target for target id collapse
  • Javascript; each, if statement, understanding in localStorage
  • Jquery; selection and on click

Script

 let collFilter = $('.accordion-button');
 collFilter.each(function(){
     let collapse = ($(this).attr('data-bs-target'));
     let viewColl = $(this).attr('data-bs-target').replace('#',''); 

     //set first time check
      let cek = localStorage.getItem(viewColl);
      if (cek == 'false'){ 
        $(`#${viewColl}`).removeClass('show');
        $(`[data-bs-target="${collapse}"]`).attr('aria-expanded', 'false')
        $(`[data-bs-target="${collapse}"]`).addClass('collapsed')
      }

     //handle store status collapse
     $(`[data-bs-target="${collapse}"]`).on('click', function(){
        let stat = $(this).attr('aria-expanded')
        localStorage.setItem (viewColl, stat);
     });
 });

Enter fullscreen mode Exit fullscreen mode

The principle of this script

Retrieve attribute data contained in data-bs-target then to do each to handle all collapses at once. After that use the localStore js function to save the collapse state contained in aria-expanded. When it is saved, window will check all localStore which is false, if false script will handle css to uncollapse (in my case default collapse is open/show)

Bonus

Make my collapse automatic close in mobile view; like in archive.org.

if (window.screen.width <= 768) {
  $('.accordion-collapse').removeClass('show');
}
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay