JSFiddle - React, Tailwind, and code Playground
by lollero
HTML
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<div id="tabs">
<div data-link="Tab 1">
Tab - 1
</div>
<div data-link="Tab 2">
Tab - 2
</div>
<div data-link="Tab 3">
Tab - 3
</div>
<div data-link="Tab 345768">
Tab - 234576213
</div>
</div>
CSS
#tabs-nav {
overflow: auto;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#tabs-nav li {
float: left;
background: #333;
color: #fff;
border-radius: 10px 10px 0px 0px;
padding: 5px 5px 2px 5px;
margin-right: 5px;
cursor: pointer;
}
#tabs-nav .selected {
background: orange;
}
#tabs {
padding: 7px;
border: 4px solid #333;
}
JavaScript
// When document is ready...
$(document).ready(function() {
var tabs = $('#tabs'),
tChild = tabs.children();
// Hide every tab container, except the first one.
tChild.filter(':not(:first)').hide();
// Generates navigation.
$('<ul id="tabs-nav"></ul>').insertBefore( tabs );
var tabsNav = $('#tabs-nav');
tChild.each(function() {
var tContent = $(this),
tContentD = tContent.data();
$('<li>'+ tContentD.link +'</li>').appendTo( tContent.closest( tabs ).prev( tabsNav ) );
});
var tpCookie = $.cookie("tabPos");
// If cookie is set....
if ( tpCookie !== null ) {
// Find tabs content with corresponding id.
var tab = tChild.eq( tpCookie );
tChild.hide();
tabsNav.find('li:nth-child('+ ( parseInt( tpCookie ) + 1 ) +')').addClass('selected')
tab.show();
}
// Click event.
tabsNav.find('li').on("click", function() {
var navli = $(this),
navliI = navli.index(),
tab = tChild.eq( navliI );
tChild.hide();
navli.addClass('selected').siblings().removeClass('selected');
tab.show();
// Set a cookie, so that we can maintain the opened tab content even if page is refreshed.
$.cookie("tabPos", navliI );
});
/*
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("tabs") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
*/
});