Skip to content

Maintaining unique tab state  #4

@bradleyburgess

Description

@bradleyburgess

This is great. Thank you.

But here's a feature I would love: maintained tab state.

Let's say we have a site for a Bed & Breakfast (fakebnb.com), and on one page (fakebnb.com/rooms) we have the different rooms — each room on a different tab panel. I, a potential guest, go to the site, and really like room no. 2. While on room 2's tab, I send my wife the link in the url bar (fakebnb.com/rooms) — except when she opens it, it obviously shows room no. 1, because it's the first tab.

Because you're doing event.preventDefault() when the tab buttons are clicked (or similarly via keyboard), the tab id isn't being pushed to history. It would be great if we could have the active tab reflected in the history. That way, when you click a tab, it gets pushed to the history (fakebnb.com/rooms#room-2), and when that link is shared, it opens to the "right" tab.

I would propose something like this (obviously tidied up):

// at the end of `_init()` method:
const hash = location.hash;
const tabPanelIds = Array.from(this.panels).map(panel => panel.id);
if (hash && tabPanelIds.includes(hash?.substr(1)) {
  this.activateTab(Array.prototype.find.call(this.buttons, button => button.href.endsWith(hash), false);
}

// at the end of `activateTab()` method:
if (location.hash?.substr(1) !== controls) {
  history.replaceState({}, "", "#" + controls);
}

Granted, I haven't tested this yet. But would you be open to a PR that implements this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions