I've been using tabs from codrops Tab Styles Inspiration and I need to be able to open specific tabs on urls.
Basically if I wanted to open tab3, I would link www.google.com/index#tab3.
Here is my code:
<div class="tabs tabs-style-topline">
<nav>
<ul>
<li><a href="#section-topline-1"><span>Overview</span></a></li>
<li><a href="#section-topline-2"><span>Register</span></a></li>
<li><a href="#section-topline-3"><span>Exhibitors</span></a></li>
</ul>
</nav>
<div class="content-wrap">
<section id="section-topline-1">Test 1</section>
<section id="section-topline-2">Test 2</section>
<section id="section-topline-3">Test 3</section>
</div><!-- /content -->
</div><!-- /tabs -->
And here is the javascript:
;( function( window ) {
'use strict';
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function CBPFWTabs( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
CBPFWTabs.prototype.options = {
start : 0
};
CBPFWTabs.prototype._init = function() {
// tabs elems
this.tabs = [].slice.call( this.el.querySelectorAll( 'nav > ul > li' ) );
// content items
this.items = [].slice.call( this.el.querySelectorAll( '.content-wrap > section' ) );
// current index
this.current = -1;
// show current content item
this._show();
// init events
this._initEvents();
};
CBPFWTabs.prototype._initEvents = function() {
var self = this;
this.tabs.forEach( function( tab, idx ) {
tab.addEventListener( 'click', function( ev ) {
ev.preventDefault();
self._show( idx );
} );
} );
};
CBPFWTabs.prototype._show = function( idx ) {
if( this.current >= 0 ) {
this.tabs[ this.current ].className = this.items[ this.current ].className = '';
}
// change current
this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
this.tabs[ this.current ].className = 'tab-current';
this.items[ this.current ].className = 'content-current';
};
// add to global namespace
window.CBPFWTabs = CBPFWTabs;
})( window );
Sorry I'm not much a jquery guy and have been trying to find a solution all day and made an account just to ask this. Thanks in advance for your help.
Maybe just listen to window.hashchange
event do the trick, no click handlers on nav > li > a
!. The jQuery way:
$(function(){
$(window).on('hashchange', function(e) {
var hash = window.location.hash;
// first reset classes
$('nav li').removeClass('tab-current');
$('.content-wrap section').removeClass('content-current');
$('nav li a[href="' + hash + '"]').parents('li').addClass('tab-current');
$('section[id="' + hash.replace('#', '') + '"]').addClass('content-current');
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.