Search code examples
javascriptlocal-storageevent-delegation

how to store click event in local storage


How to store click event in a local storage to use it after page refresh.

const container = document.querySelector('.filter ul');

container.addEventListener('click',(event) =>{
  const closest = event.target.closest('.accordion-header');
  if (!closest) return;
  closest.classList.add('active');
  closest.nextElementSibling.classList.add('active');
});
<div class = "filter">
  <ul>
    <li>
     <h4 class = ""> Accordion </h4>
     <p> Hello,world </p>
    </li>

  </ul>
 </div>


Solution

  • You can use the localStorage API. You can save the state of the active class for each accordion header and its sibling in local storage, so that you can retrieve it after the page refreshes.

    const container = document.querySelector('.filter ul');
    
    container.addEventListener('click', (event) => {
      const closest = event.target.closest('.accordion-header');
      if (!closest) return;
    
      closest.classList.add('active');
      closest.nextElementSibling.classList.add('active');
      
      // Store the state of the accordion header and its sibling in local storage
      localStorage.setItem('accordion-header-state', JSON.stringify({
        headerClassList: Array.from(closest.classList),
        siblingClassList: Array.from(closest.nextElementSibling.classList),
      }));
    });
    
    // Retrieve the state from local storage after page refresh
    const savedState = JSON.parse(localStorage.getItem('accordion-header-state'));
    if (savedState) {
      const header = document.querySelector('.accordion-header');
      const sibling = header.nextElementSibling;
    
      header.classList.add(...savedState.headerClassList);
      sibling.classList.add(...savedState.siblingClassList);
    }