MicroMan
MicroMan

Reputation: 2098

Href # Link on page Requires back button to be hit twice on browser

I have some tabs on a page and there is a href to get to specific parts of the page.

<a class="page_link" href="#tabA">Section1</a>

All the content is on the same page and the link is just to part of the page. This then updates the url with #tabA

If i hit the back button on the browser i have to hit it twice to get back to the previous page. Is there any way to prevent having to hit back twice?

There is also some JS in order to track the history

const hash = window.location.hash ? window.location.hash.substr(1) : false;
const panel = hash ? document.getElementById(hash) : false;
const link = hash ? self.querySelector(`[href='#${hash}']`) : false;

window.history.pushState(null, null, panelId);

I have the following to close and open the tab, but nothing to pop history or replace it, is something missing

const openPanel = (self, link, target) => {
  closeActiveTab(self);

  link.classList.add('activeTab');

  link.setAttribute('aria-selected', 'true');
  target.classList.add('activeTab');
  target.setAttribute('aria-hidden', 'false');

};

const closeActiveTab = (el) => {
  const tabs = el.getElementsByClassName('activeTab');
  while (tabs.length) {

    const selTab = tabs[0];

    selTab.classList.remove('activeTab');
    selTab.setAttribute('aria-selected', 'false');
  }

};

Upvotes: 2

Views: 1163

Answers (1)

Roman Spiridonov
Roman Spiridonov

Reputation: 436

The best way is to try doesn't change the url at all. You can scroll to anchor section or show tab without changing page hash. If it isn't required, ofcourse.

If it is required to have a hash in the url, you can use history.replaceState() instead of history.pushState(). This method will replace current state and to go back you can press the back button once as you wanted.

Upvotes: 1

Related Questions