-1

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>
rocky
  • 23
  • 6

2 Answers2

1

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);
}
tdy
  • 36,675
  • 19
  • 86
  • 83
1

It sounds like you're not trying to store the click (event), but instead the fact that this item has been clicked and store it through page refresh.

In your click handler you'd need to add a line that stores the clicked state to local storage.

localStorage.setItem('itemClicked', 'true');

Note that localStorage only stores strings. Here we're storing an item in sotrage called itemClicked and giving it the value true.

On page load, you'd then need to check local storage and run classList.add('active') again on the element. In an onload function you'd check for this item as follows

localStorage.getItem('itemClicked') === 'true';
NetByMatt
  • 703
  • 4
  • 13