DEV Community


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


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


  • 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


 let collFilter = $('.accordion-button');
     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'){ 
        $(`[data-bs-target="${collapse}"]`).attr('aria-expanded', 'false')

     //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)


Make my collapse automatic close in mobile view; like in

if (window.screen.width <= 768) {
Enter fullscreen mode Exit fullscreen mode

Top comments (0)