Skip to content

Instantly share code, notes, and snippets.

@wesamly
Last active October 13, 2016 20:53
Show Gist options
  • Save wesamly/03491ebf53e17c75480b8d2de1bf230c to your computer and use it in GitHub Desktop.
Save wesamly/03491ebf53e17c75480b8d2de1bf230c to your computer and use it in GitHub Desktop.
WordPress Admin Page with simple Javascript tabs
<div class="wrap">
<h1>My Plugin Admin Page</h1>
<h2 class="nav-tab-wrapper">
<a class="nav-tab nav-tab-active" href="#tab1">Tab 1</a>
<a class="nav-tab" href="#tab2">Tab 2</a>
</h2>
<div id="tab1">
<h3>Tab 1 Content</h3>
</div>
<div id="tab2">
<h3>Tab 2 Content</h3>
</div>
</div>
<script>
var tabs;
/**
* Get Tab Key
*/
function getTabKey(href) {
return href.replace('#', '');
}
/**
* Hide all tabs
*/
function hideAllTabs() {
tabs.each(function(){
var href = getTabKey(jQuery(this).attr('href'));
jQuery('#' + href).hide();
});
}
/**
* Activate Tab
*/
function activateTab(tab) {
var href = getTabKey(tab.attr('href'));
tabs.removeClass('nav-tab-active');
tab.addClass('nav-tab-active');
jQuery('#' + href).show();
}
jQuery(document).ready(function($){
var activeTab, firstTab;
// First load, activate first tab or tab with nav-tab-active class
firstTab = false;
activeTab = false;
tabs = $('a.nav-tab');
hideAllTabs();
tabs.each(function(){
var href = $(this).attr('href').replace('#', '');
if (!firstTab) {
firstTab = $(this);
}
if ($(this).hasClass('nav-tab-active')) {
activeTab = $(this);
}
});
if (!activeTab) {
activeTab = firstTab;
}
activateTab(activeTab);
//Click tab
tabs.click(function(e) {
e.preventDefault();
hideAllTabs();
activateTab($(this));
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment