Multiple actions on click - ordering issue

Hi!

When the user clicks on a link to a subpage, I want to store data in sessionStorage from the current page before leaving to the next page. Then when this new page has loaded, I want to apply the sessionStorage data on this page.

What complicates things is that the link is part a collapsing menu system. Which means that this system needs to update (which is also done on click) before the page data is stored.

So essentially, the wanted execution order:

  • User clicks link
  • Menu system is updated
  • Page data is stored
  • Browser loads the new page
  • Page data from the previous page loads and applies on the new page

My issue is the order in which everything is executed. I don’t understand when the user clicks on the link how to control the order of when the actions are executed.

Thankful for help

You need to prevent to either default behavior or execute your code before allowing the click handler to finish.

<a href="link/to/my/page" class="menu-link">My Page</a>
<a href="link/to/my/other/page" class="menu-link">My Other Page</a>
const logLink = (event) => {
  event.preventDefault();
  event.stopPropagation();
  console.log(event.target.text, event.target.href);
}

[...document.querySelectorAll('.menu-item')].forEach(element => {
  element.addEventListener('click', logLink);
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.