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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

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

Okay