Utilizing the Flickity plugin, I have successfully created a tab-based content carousel. By incorporating the hash script available on GitHub, users can directly access a specific tab using URLs like example.com/#slide-1.
However, I am facing an issue where upon navigating away from the page and returning or refreshing it, the 'is-selected' class on 'tab-nav' resets itself. As a result, the selected tab does not correspond to the loaded content.
I am seeking a JavaScript solution that would allow the browser to remember the last 'is-selected' position so that when users refresh the page or return to it, the correct tab is still highlighted.
.slide-content {
width: 100%;
}
.tab-nav a,
.tab-nav a:visited,
.tab-nav a:focus,
.tab-nav a:hover {
display: inline-block;
color: #000;
text-decoration: none;
padding: 24px;
border: 1px solid #dedede;
}
.tab-nav .is-selected {
background: #dedede;
}
<link href="https://unpkg.com/flickity@2/dist/flickity.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
<script src="https://unpkg.com/flickity-hash@1/hash.js"></script>
<nav class="tab-nav">
<a class="slide is-selected" href="#slide-1">Slide One</a>
<a class="slide" href="#slide-2">Slide Two</a>
<a class="slide" href="#slide-3">Slide Three</a>
<a class="slide" href="#slide-4">Slide Four</a>
<a class="slide" href="#slide-5">Slide Five</a>
</nav>
<div class="carousel">
<div class="slide-content" id="slide-1">
<p>I'm Slide One</p>
</div>
<div class="slide-content" id="slide-2">
<p>I'm Slide Two</p>
</div>
<div class="slide-content" id="slide-3">
<p>I'm Slide Three</p>
</div>
<div class="slide-content" id="slide-4">
<p>I'm Slide Four</p>
</div>
<div class="slide-content" id="slide-5">
<p>I'm Slide Five</p>
</div>
</div>
<script>
var utils = window.fizzyUIUtils;
var carousel = document.querySelector('.carousel');
var flkty = new Flickity( carousel, {
prevNextButtons: false,
pageDots: false,
hash: true
});
// Elements
var cellsButtonGroup = document.querySelector('.tab-nav');
var cellsButtons = utils.makeArray( cellsButtonGroup.children );
// Update buttons on select
flkty.on( 'select', function() {
var previousSelectedButton = cellsButtonGroup.querySelector('.is-selected');
var selectedButton = cellsButtonGroup.children[ flkty.selectedIndex ];
previousSelectedButton.classList.remove('is-selected');
selectedButton.classList.add('is-selected');
});
// Cell select
cellsButtonGroup.addEventListener( 'click', function( event ) {
if ( !matchesSelector( event.target, '.slide' ) ) {
return;
}
var index = cellsButtons.indexOf( event.target );
flkty.select( index );
});
</script>