DEV Community

andysaktia
andysaktia

Posted on • Updated on

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

Top comments (0)