Notification texts go here Contact Us Buy Now!

How to keep the current Accordion active on page refresh in Bootstrap

First, you add the id (which div you want to show) into the session.
Then, after reload, you just get the session. and show the current div by JS. Here is my code to do this.
$(document).ready(function() {
  // Get saved data from sessionStorage
  let selectedCollapse = sessionStorage.getItem('selectedCollapse');
  if(selectedCollapse != null) {
    $('.accordion .collapse').removeClass('show');
    $(selectedCollapse).addClass('show');
  }
  //To set, which one will be opened
  $('.accordion .btn-link').on('click', function(){ 
    let target = $(this).data('target');
    //Save data to sessionStorage
    sessionStorage.setItem('selectedCollapse', target);
  });
});

Note that, Based on your code, I think you used bootstrap and jquery. You must need the jquery at least to perform the above actions.

I don't know if this is the right way or not, but it will work somehow.
This is a very simple method:
$("#").load(location.href + " #");
Always give space just before the second # sign, otherwise, the above code will return the whole page.
I found this post particularly helpful when solving my own Bootstrap Accordion problem where AJAX is not an option. I do, however, want to expand the code a little that hasan05 provided. I basically added checks to see if the user navigated away from the page completely, or just reloaded it (say a postback operation for instance). I set mine to destroy session data after 3 seconds. It is generally good practice to destroy your sessionStorage if you are no longer using them.
//:: Accordion check: Saves current accordion tab state in a session, so it can be returned to on page reload
function setAccordionSession() {
    let selectedAccordion = sessionStorage.getItem('selectedAccordion');

    //:: if sessionStorage has a value, choose that header to expand
    if (selectedAccordion != null) {
        $('.accordion .collapse').removeClass('show');
        $('.accordion-button').attr('aria-expanded', false);
        $('.accordion-button').addClass('collapsed');

        $(selectedAccordion).addClass('show');
        $(selectedAccordion).attr('aria-expanded', true);

        //:: Loop through each Accordion Button to see if data-bs-target exists and remove collapsed class 
        $.each($('.accordion-button'), function () {
            if ($(this).is('[data-bs-target="' + selectedAccordion + '"]')) {
                $(this).removeClass('collapsed');
            }
        });
    }
    //:: no sessionStorage value present, therefore we must want the default accordion views
    else {            
        $('div#collapseOne').addClass('show');
        $('h2#headingOne > button').attr('aria-expanded', true);
        $('h2#headingOne > button').removeClass('collapsed');
    }
};

//:: When one clicks the accordion button/tab, save its current data-bs-target value to sessionStorage
$('.accordion .accordion-button').on('click', function () {
    let target = $(this).data('bs-target');
    sessionStorage.setItem('selectedAccordion', target);        
});

//:: When User navigates away from page, take a stamp of current Date/Time
$(window).on("beforeunload", function () {
    window.localStorage.unloadTime = JSON.stringify(new Date());        
})
//:: Check unload time vs load time to determine if sessions should be cleared or not.
window.onload = function () {
    let loadTime = new Date();
    let unloadTime = new Date(JSON.parse(window.localStorage.unloadTime));
    let refreshTime = loadTime.getTime() - unloadTime.getTime();        

    //:: If user was gone more than 3 seconds, clear the sessionStorage and generate accordions with defaults
    if (refreshTime > 3000) {            
        sessionStorage.clear();
        setAccordionSession();
    }
    else {
        //:: Page must have been refreshed, maintain current state using existing sessionStorage
        setAccordionSession();
    }
};
For people looking for a solution in react, they can use it like that:
const accordionLocalStorageKey = 'cachedAccordionKey'

const getLastActiveKeyOfAccordionOnLinksPage = () => localStorage.getItem(accordionLocalStorageKey)
const setLastActiveKeyOfAccordionOnLinksPage = (value) => localStorage.setItem(accordionLocalStorageKey, value)

const LearnAccordion = () => {
  const [activeKey, setActiveKey] = useState(getLastActiveKeyOfAccordionOnLinksPage)
  const handleSelect = (value) => {
    setLastActiveKeyOfAccordionOnLinksPage(value)
    setActiveKey(value)
  }
  return <div>
    <Accordion activeKey={activeKey} onSelect={handleSelect}>
      <Accordion.Item eventKey="0">
        <Accordion.Header id={"accordionHeader"}>Accordion Item #1</Accordion.Header>
        <Accordion.Body>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
        </Accordion.Body>
      </Accordion.Item>
    </Accordion>
  </div>
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.