I have a navigation tabs and when user clicks a tab the div changes with ajax. I would like to it to remember on what tab user was when user changes page. I havent done the tab navigation and im totally new to javascript/jquery. Here is the javascript for the tabs:
jQuery('#contentContainer #tabNavi .nav-item').each(function(i, item) {
jQuery(item).bind('click', function() {
if (jQuery('a', this).hasClass('activeTab')) {
return;
} else {
jQuery('#contentContainer #tabNavi .nav-item' a').removeClass('activeTab').eq(i).addClass('activeTab');
channel_id = jQuery('a', this).attr('href').split('#')[1];
if (channel_id == _channel) {
return;
}
}
})
});
The nav links are like this:
<li>Link1</li>
<li>Link2</li
Now I have the href value saved in a cookie but i dont know how can i change the active class to right li item when user comes on page and he has been on site before and he has clicked some tab.
Put this code after click event initialization (jQuery(item).bind('click', function() {...})
var selectedTab = $.cookie('selectedTab');
if (selectedTab) {
$('li[href="' + selectedTab + '"]').click();
}
UPD
A bit modified code
(function($) {
$('#contentContainer #tabNavi .nav-item a').click(function() {
var $link = $(this);
$link.click(function() {
if (!$link.hasClass('activeTab')) {
$('#contentContainer #tabNavi .nav-item a.activeTab').removeClass('activeTab');
$link.addClass('activeTab');
$.cookie('selected-tab', $link.attr('href'));
}
return false;
});
});
var selectedTab = $.cookie('selected-tab');
if (selectedTab) {
$('#contentContainer #tabNavi .nav-item a[href="' + selectedTab + '"]').click();
}
})(jQuery);
Related
I have a responsive menu. When the menu reaches tablet/mobile width it turns into a mobile menu. In the menu are 2 special buttons. #toggleReg and #toggleLogin
When the menu dropdown is Open. #toggleReg and #toggleLogin are set to .show but when the menu dropdown is closed they are set to .hide ... simple enough.
But because this is part of a responsive menu. I need #toggleReg and #toggleLogin to always .show if the browser viewports width is above 768px;
How do I add a condition that will solve this problem for me. Since it is currently set to be hidden once reaching a width below 768px; via a media query and then told to display again if the mobile menu is "opened" via the js snippet below.
Here is my current code.
$.fn.menumaker = function(options) {
var cssmenu = $(this), settings = $.extend({
title: "Menu",
format: "dropdown",
sticky: false
}, options);
return this.each(function() {
cssmenu.prepend('<div id="menu-button">' + settings.title + '</div>');
$(this).find("#menu-button").on('click', function(){
$('#toggleReg').hide();
$('#toggleLogin').hide();
$(this).toggleClass('menu-opened');
var mainmenu = $(this).next('ul');
if (mainmenu.hasClass('open')) {
mainmenu.hide().removeClass('open');
}
else {
mainmenu.show().addClass('open');
$('#toggleReg').show();
$('#toggleLogin').show();
if (settings.format === "dropdown") {
mainmenu.find('ul').show();
}
}
});
I am working with cssmenumaker source file
Thanks for any help!
I think if you just handle the window size before your allow the click, you should be able to make sure the buttons show up. Then if the window is smaller, it will check for the button being pressed.
$.fn.menumaker = function(options) {
var cssmenu = $(this), settings = $.extend({
title: "Menu",
format: "dropdown",
sticky: false
}, options);
return this.each(function() {
cssmenu.prepend('<div id="menu-button">' + settings.title + '</div>');
//Add this clause
if($(window).width() >= 768){
$('#toggleReg').show();
$('#toggleLogin').show();
} else {
$(this).find("#menu-button").on('click', function(){
$('#toggleReg').hide();
$('#toggleLogin').hide();
$(this).toggleClass('menu-opened');
var mainmenu = $(this).next('ul');
if (mainmenu.hasClass('open')) {
mainmenu.hide().removeClass('open');
} else {
mainmenu.show().addClass('open');
$('#toggleReg').show();
$('#toggleLogin').show();
if (settings.format === "dropdown") {
mainmenu.find('ul').show();
}
}
}
});
}
This won't work on window resize though - only when the window loads.
UPDATE
This is how I would normally write it:
function menuState() {
var winW = $(window).width();
if(winW >= 768) {
//Handle Large Menu
$('#toggleReg').show();
$('#toggleLogin').show();
} else {
//Handle Mobile Menu
$('#toggleReg').hide();
$('#toggleLogin').hide();
$(document).on('click', '#menu-button', function() {
var menuClass = $(this).attr('class').split(" ")[1];
if(menuClass == "menu-opened") {
$(this).removeClass('menu_opened');
$(this).next('ul').removeClass('open');
} else {
$(this).addClass('menu-opened');
var mainMenu = $(this).next('ul');
if(mainMenu.hasClass('open')) {
mainMenu.hide().removeClass('open');
} else {
mainMenu.show().addClass('open');
$('#toggleReg').show();
$('#toggleLogin').show();
if (settings.format === "dropdown") {
mainmenu.find('ul').show();
}
}
}
});
}
}
$(document).ready(function(){
menuState();
});
$(window).resize(function(){
menuState();
});
You may be able to comment out the function and just plaster this in that javascript file.
I'm using jquery UI to create tabs. Requirement is when i select tab2 or any other tab and reload/refresh the page, focus should be on the selected tab. Please find the fiddle http://jsfiddle.net/CnEUh/500/
I have gone through many online forums but could not get the expected result.
I followed the link Set Jquery ui active tab on page load/reload , but didn't got the result.
Tried the below code :
$(document).ready(function() {
$("#tabs").tabs({active: tabs-2});
// Set active tab on page load
var SelectedTab = tabs-2;
if(tabSelectedId!=""){
$("#tabs").tabs({selected: tabSelectedId});
}
});
Please suggest how can i keep the focus on the selected tab on page reload. My fiddle http://jsfiddle.net/CnEUh/500/
You can accomplish it by using location.href
On click, just add #tab=2 and then on page load, here you can retrieve location.href and choose which tav is selected.
Add jquery.cookie.js library and the following code
$(document).ready(function() {
var $tabs = $( "#tabs" ).tabs({
activate: function(event ,ui){
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
var selectedIndex=parseInt($.cookie('active_tab'));
if(selectedIndex) {
$tabs.tabs({ active: selectedIndex });
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
// set cookie on tab select
});
Or without jquery.cookie.js, pass the active tab index as a parameter
var activeTab;
var $tabs = $("#tabs").tabs({
activate: function (event, ui) {
activeTab = ui.newTab.index();
}
});
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var selectedIndex = parseInt(params.selectedIndex);
if (selectedIndex) {
$tabs.tabs({
active: selectedIndex
});
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
$('#tabs').click(function() {
window.location.href = window.location.href.replace( /[\?#].*|$/, "?selectedIndex="+activeTab );
});
Hopefully it works.
Thanks
I'm trying to add an active class (i.e. class="active") to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I've tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?
<ul id="nav">
<li id="navhome">Home</li>
<li id="navmanage">Manage</li>
<li id="navdocso">Documents</li>
<li id="navadmin">Admin Panel</li>
<li id="navpast">View Past</li>
</ul>
Here is an example of the javascript that I'm putting in my head tag in my site master. What am I doing wrong?
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
.active, a.active {
color: red;
}
a {
color: #337ab7;
text-decoration: none;
}
li{
list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3>
<ul>
<li>Home</li>
<li>About</li>
</ul>
<h2>Live Demo</h2>
With VANILLA plain JavaScript
(function () {
var current = location.pathname.split('/')[1];
if (current === "") return;
var menuItems = document.querySelectorAll('.menu-item a');
for (var i = 0, len = menuItems.length; i < len; i++) {
if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
menuItems[i].className += "is-active";
}
}
})();
ES6 version, that works properly in cases when your link is to "/products" and you have subroutes, like: "/products/new", "/products/edit", etc.
let switchNavMenuItem = (menuItems) => {
var current = location.pathname
$.each(menuItems, (index, item) => {
$(item).removeClass('active')
if ((current.includes($(item).attr('href')) && $(item).attr('href') !== "/") || ($(item).attr('href') === "/" && current === "/")){
$(item).addClass('active')
}
})
}
$(document).ready(() => {
switchNavMenuItem($('#nav li a, #nav li link'))
})
If your menu need add the active class in li, you need use this code above.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
$(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
$( ".top-menu li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd)
$(this).addClass('active')
});
});
This on page JS code is a 100% working put your id and enjoy it.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
console.log(CurrentUrlEnd);
$( "#lu-ID li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd){
$(this).closest('li').addClass('active')
}
});
});
None of the above solutions worked for me. Finally this javascript solution worked.
<script>
function setActive() {
linkObj = document.getElementById('premier-topnav').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
if(document.location.href.indexOf(linkObj[i].href)>=0) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
</script>
premier-topnav is the id of navbar div.
.active class is defined as:
#premier-topnav .active {
color: brown;
}
var cururl = window.location.pathname;
var curpage = cururl.substr(cururl.lastIndexOf('/') + 1);
var hash = window.location.hash.substr(1);
if((curpage == "" || curpage == "/" || curpage == "admin") && hash=="")
{
//$("nav .navbar-nav > li:first-child").addClass("active");
}
else
{
$(".topmenu li").each(function()
{
$(this).removeClass("active");
});
if(hash != "")
$(".topmenu li a[href*='"+hash+"']").parents("li").addClass("active");
else
$(".topmenu li a[href*='"+curpage+"']").parents("li").addClass("active");
}
Rob.M got it right.
I'm just going to post my solution since his didn't really work for me. i have a small change in comparison to him. assuming you have different paths to each link.
(function() {
var current = location.pathname;
$('#navbar ul li a').each(function() {
var $this = $(this);
// we check comparison between current page and attribute redirection.
if ($this.attr('href') === current) {
$this.addClass('active');
}
});
})();
This worked perfectly for me.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).addClass('active');
}
});
});
I know it been quite a while this question was asked. Here is the answer which will work without jQuery:
var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');
Hope this helps.
If you want for master page in asp .net just put this code inside body tag
<script type="text/javascript">
jQuery(function ($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function () {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
Thank you
This should do your job in one liner.
document.querySelector(`a[href^='${location.pathname.split('/'[1])}']`).className = 'active'
jQuery style:
$('a[href="'+ window.location.href + '"]').css({
backgroundColor: 'red',
color: 'white'
})
In first line use this if you have relative links
$('a[href="'+ window.location.path + '"]').css({
Or both
$('a[href="'+ window.location.href + '"], a[href="'+ window.location.path + '"]').css({
$(function(){
//this returns the whole url
var current = window.location.href;
//this identifies the list you are targeting
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is exactly like this link, make it active
if($this.attr('href') === current){
//this takes care of ul inside a ul, it opens and make active the selected li
$this.parents('.dropdown-menu').toggle();
$this.css('color', 'red');
}
})
});
The bellow jquery script will match the manu if the page has any query string parameter as well. This script is helpful for links with nearly same name.
<script>
//select current menu Item
$(function () {
var current = location.pathname.toLocaleLowerCase();
$('.sidebar li a').each(function () {
var $this = $(this);
var href = $this.attr('href');
href = href.replace(/\?.*/, "").toLocaleLowerCase();
// if the current path is equal to this link, make it active
if (href === current) {
$this.addClass('active');
}
})
})
</script>
Accessible Version:
Here's an accessible version inspired by rob.
I didn't want to run this script on the homepage so I check if it's the homepage
I check if the link matches the exact page instead of checking if it's included in the path. Or else you would get multiple items in the query.
JS
function activateCurrentPage(menuItems){
var current = location.pathname;
if (current !== "/") {
menuItems.each(function(){
var $this = $(this);
if($this.attr('href') === current){
$this.addClass('active');
$this.attr('aria-current', 'page');
}
});
};
}
activateCurrentPage( $('#nav li a') );
CSS
Then for CSS don't target the active class instead target the aria attribute.
#nav a[aria-current="page"]{
color:red;
}
Saw somethng wth plain Javascript
https://www.youtube.com/watch?v=BI3kNsTruWo&ab_channel=OnlineTutorials
Put it in <script> tags after header in my Wordpress site
(function () {
const currentLocation = location.href;
console.log(currentLocation);
const menuItem = document.getElementsByClassName('nav-item');
const menuLength = menuItem.length
for ( i = 0; i < menuLength; i++){
if(menuItem[i].href === currentLocation){
menuItem[i].className += " active"
}
}
})();
<a class="nav-item" href="/ideja/">Ideja</a>
<a class="nav-item" href="/piesaki-sapni/">Piesaki Sapni</a>
<a class="nav-item" href="/uznemejiem/">Uzņēmējiem</a>
<a class="nav-item" href="/sapnu-banka/">Sapņu banka</a>
<a class="nav-item" href="/sapnus-atbalsta/">Sapņus atbalsta</a>
<a class="nav-item" href="/99-iedvesmas-stasti/">99 iedvesmas stāsti</a>
<a id="lv" class="active" href="#">LV</a>
<a href="javascript:void(0);" class="icon" onclick="openNavbar()">
<div id="hamburger" class="hamburger "></div>
</a>
i was having troubles where the link to the root would light up if any page was selected when using Networker's example. this will prevent that for the root pae:
function setActive() {
linkObj = document.getElementById('menu').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
const url = new URL(window.location.href);
if((document.location.href.indexOf(linkObj[i].href)>=0 && linkObj[i].href != url.protocol+"//"+url.hostname+"/") || document.location.href == linkObj[i].href) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
This Does the Job Done For me...
Put this before the ending of body tag
$(function () {
var current = location.pathname;
console.log(current);
if (current == "/") {
$('#home').addClass('active'); //#home is the id for root link.
}
else {
$('#navbarCollapse div a').each(function () {
var $this = $(this);
// if the current path is like this link, make it active
if ($this.attr('href').indexOf(current) !== -1) {
$this.addClass('active');
}
})
}
})
Classes can make the life a whole way easier.
css
<nav>
<ul class="nav-list">
<li class="nav-list-item"><a class="nav-link nav-link-active" href="index.html">Home</a></li>
<li class="nav-list-item"><a class="nav-link" href="about.html">About Me</a></li>
<li class="nav-list-item"><a class="nav-link" href="posts.html">Recent Posts</a></li>
</ul>
</nav>
js
(function() {
current_page = window.location.href;
navlinks = document.getElementsByClassName("nav-link");
active_page = document.getElementsByClassName("nav-link-active")[0];
if (active_page) {
active_page.classList.remove("nav-link-active");
}
for (i=0; i < navlinks.length; i++) {
if (navlinks[i].href == current_page) {
navlinks[i].classList.add("nav-link-active");
break;
}
}
})();
I know this is late answer but this works ok for me
var links = document.querySelectorAll('li a');
for (link of links) {
if (window.location.pathname == link.getAttribute('href')) {
link.classList.add('active')
} else {
link.classList.remove('active')
}
}
Below is the solution to add the dynamic active class to the navbar elements.
// first lets get all the navbar elements.
const navElements = document.querySelectorAll(".list");
// creating a function of active navbar item
const activeLink = (el) => {
list.forEach((item) => {
item.classList.remove("active");
el.classList.add("active");
});
};
// attaching the event listener for each element
list.forEach((item) => {
item.addEventListener("click", () => {
activeLink(item)
});
});
Inside my function.js file I have two functions: the first one loads my pages using ajax. The other one is for minipulating tabbed content on my home page. Initially, both the functions work. However, when I click on any one of the menu bar links, and then click on the home link to return back to the home page, my tabbed area no longer works. I have a feeling that the organictabs() function is only getting called when index.html is first loaded. How can I change this so that organictabs() is called every time a new page is loaded?
// remap jQuery to $
(function($){})(window.jQuery);
/* trigger when page is ready */
$(document).ready(function (){
initialize();
});
function initialize() {
//Click on nav to load external content through AJAX
$('#topnav a, #bottomnav a').not('#bottomnav #fbcallus a').click(function(e){
e.preventDefault();
$('#pages').load( e.target.href + ' #loadcontent'); //pages finished loading
}); //clicked on nav
//handle AJAX for left nav
$(function() {
$("#tabedarea").organicTabs();
});
}
//Click on nav to load external content through AJAX
// $('#topnav a').click(function(e){
// e.preventDefault();
// $('#pages').load( e.target.href + ' #loadcontent'); //pages finished loading
// }); //clicked on nav
(function($) {
$.organicTabs = function(el, options) {
var base = this;
base.$el = $(el);
base.$navtabs = base.$el.find(".navtabs");
base.init = function() {
base.options = $.extend({},$.organicTabs.defaultOptions, options);
// Accessible hiding fix
$(".hidetabs").css({
"position": "relative",
"top": 0,
"left": 0,
"display": "none"
});
base.$navtabs.delegate("li > a", "click", function() {
// Figure out current list via CSS class
var curList = base.$el.find("a.current").attr("href").substring(1),
// List moving to
$newList = $(this),
// Figure out ID of new list
listID = $newList.attr("href").substring(1),
// Set outer wrapper height to (static) height of current inner list
$allListWrap = base.$el.find(".list-wrap"),
curListHeight = $allListWrap.height();
$allListWrap.height(curListHeight);
if ((listID != curList) && ( base.$el.find(":animated").length == 0)) {
// Fade out current list
base.$el.find("#"+curList).fadeOut(base.options.speed, function() {
// Fade in new list on callback
base.$el.find("#"+listID).fadeIn(base.options.speed);
// Adjust outer wrapper to fit new list snuggly
//var newHeight = base.$el.find("#"+listID).height();
//$allListWrap.animate({
// height: newHeight
//});
// Remove highlighting - Add to just-clicked tab
base.$el.find(".navtabs li a").removeClass("current");
$newList.addClass("current");
});
}
// Don't behave like a regular link
// Stop propegation and bubbling
return false;
});
};
base.init();
};
$.organicTabs.defaultOptions = {
"speed": 300
};
$.fn.organicTabs = function(options) {
return this.each(function() {
(new $.organicTabs(this, options));
});
};
})(jQuery);
Making use of the complete function on the jquery load will solve your problem I believe:
function initialize() {
//Click on nav to load external content through AJAX
$('#topnav a, #bottomnav a').not('#bottomnav #fbcallus a').click(function(e){
e.preventDefault();
$('#pages').load( e.target.href + ' #loadcontent', function() { $("#tabedarea").organicTabs(); }); //pages finished loading
});
}
I just need to know if there is a more efficient way of writing this block of code for transition effects on my navigation menu. It's using ajax transitions if you're wondering why I don't just apply each class individually.
here's the javascript code:
var navA = $('#nav a'),
aboutBtn = $('#aboutBtn'),
portfolioBtn = $('#portfolioBtn'),
resumeBtn = $('#resumeBtn'),
photoBtn = $('#photoBtn');
navA.on('click', function(e) {
var $this = $(this);
e.preventDefault();
// if the resumeBtn is clicked
if ($this.attr('id') == 'resumeBtn') {
// Portfolio
portfolioBtn.removeClass('portfolioActive');
portfolioBtn.addClass('portfolio');
//About Me
aboutBtn.removeClass('aboutActive');
aboutBtn.addClass('about');
// Photo
photoBtn.removeClass('photoActive');
photoBtn.addClass('photo');
// Resume
resumeBtn.removeClass('resume');
resumeBtn.addClass('resumeActive');
}
// If portfolioBtn Is Clicked
else if ($this.attr('id') == 'portfolioBtn') {
// About
aboutBtn.removeClass('aboutActive');
aboutBtn.addClass('about');
// Resmue
resumeBtn.removeClass('resumeActive');
resumeBtn.addClass('resume');
// Photo
photoBtn.removeClass('photoActive');
photoBtn.addClass('photo');
// Portfolio
portfolioBtn.removeClass('portfolio');
portfolioBtn.addClass('portfolioActive');
}
// If photoBtn Is Clicked
else if($this.attr('id') == 'photoBtn') {
// About
aboutBtn.removeClass('aboutActive');
aboutBtn.addClass('about');
// Portfolio
portfolioBtn.removeClass('portfolioActive');
portfolioBtn.addClass('portfolio');
// Resume
resumeBtn.removeClass('resumeActive');
resumeBtn.addClass('resume');
// Photo
photoBtn.removeClass('photo');
photoBtn.addClass('photoActive');
}
// If aboutBtn is clicked
else if ($this.attr('id') == 'aboutBtn') {
// Portfolio
portfolioBtn.removeClass('portfolioActive');
portfolioBtn.addClass('portfolio');
// About Me
aboutBtn.removeClass('about');
aboutBtn.addClass('aboutActive');
// Resume
resumeBtn.removeClass('resumeActive');
resumeBtn.addClass('resume');
// Photo
photoBtn.removeClass('photoActive');
photoBtn.addClass('photo');
};
});
Html:
<div id="nav">
<a class="resume" href="resume.html" id="resumeBtn">Resume</a>
<a class="portfolio" href="portfolio.html" id="portfolioBtn">Portfolio</a>
<a class="photo" href="photos2.html" id="photoBtn">Photos</a>
<a class="aboutActive" href="index.html" id="aboutBtn">About Me</a>
</div>
The CSS classes uses images for the transitions, but either way. I just wanna know if there's a more efficient way to write my jQuery. I'm sure there is I'm just having a stupid moment. Thanks!
EDIT: I'm structuring the code differently in how it handles the panel switches and this section of code is just designed to handle the Nav transitions.
So essentially, I removed the bottom of eachIFstatement so it only handles the the nav transitions.
Well, if your panels have the same HTML structure as your navs, this will work:
$('#nav a').on('click', function (e) {
e.preventDefault();
//Buttons
$('#' + this.id).addClass('active').siblings().removeClass('active');
// Panels
$('#' + this.id.slice(0, this.id.lastIndexOf('Btn')) + 'Panel').show().siblings().hide();
notworkOn = false;
switch (this.id) {
case 'portfolioBtn':
handlePortfolio();
break;
case 'aboutBtn':
handleAbout();
break;
}
});
function handlePortfolio() { arrange(); }
function handleAbout() {
arrange();
$('#header .inner').animate({ width: '100%' }, 600);
}
That assumes your panels HTML structure is similar to your Buttons, and named resumePanel etc. Sample here: http://jsfiddle.net/9vwYm/1/
Edit: Your current code seems to have some inconsistencies in it, e.g. clicking the Photo button displays the Photo panel, and then when you click on About, the Photo panel is not hidden. Is this intentional?
A bit messy, but twice as short and wo/ repetitive error-prone parts.
var pages = [
{ title: 'about',
showPanel: aboutPanel,
dontHidePanels: [photoPanel, resumePanel],
extracode: function() {
notworkOn = false;
arrange();
$('#header .inner').animate({
width: '100%'
}, 600);
}
},
{ title: 'protfolio',
showPanel: horizon,
dontHidePanels: [resumePanel],
extracode: function() {
arrange()
notworkOn = false;
}
},
{ title: 'resume',
showPanel: resumePanel,
dontHidePanels: [servicesPanel],
extracode: function() {
notworkOn = false;
}
},
{ title: 'photo',
showPanel: photoPanel,
dontHidePanels: [resumePanel],
extracode: function() {
notworkOn = false;
}
}
];
var panels = [ aboutPanel, horizon, photoPanel, resumePanel, servicesPanel];
$('#nav a').on('click', function(e) {
e.preventDefault();
var curPageTitle = this.id.match(/(\w+)Btn/)[1];
var p = null;
for (var i = 0; i < pages.length; i++) {
if (pages[i].title == curPageTitle) {
$('#' + pages[i].title + 'Btn')
.removeClass(pages[i].title + 'Active')
.addClass(pages[i].title);
p = pages[i];
} else {
$('#' + pages[i].title + 'Btn')
.removeClass(pages[i].title)
.addClass(pages[i].title + 'Active');
}
}
for (var i = 0; i < panels.length; p++) {
if (panels[i] == p.showPanel) {
panels[i].css('display', 'block');
} else if ($.inArray(panels[i], p.dontHidePanels) != -1) {
panels[i].css('display','none');
}
}
p.extracode();
});
I would change your class structure to use a separate active class:
<div id="nav">
<a class="resume" href="resume.html" id="resumeBtn">Resume</a>
<a class="portfolio" href="portfolio.html" id="portfolioBtn">Portfolio</a>
<a class="photo" href="photos2.html" id="photoBtn">Photos</a>
<a class="about active" href="index.html" id="aboutBtn">About Me</a>
</div>
And then do this with the script (EDIT missed the fact that your header animation was only for the about, so changed that below):
$('#nav a').on('click', function(e) {
var $this = $(this);
e.preventDefault();
//Toggle active
$this.parent().find('.active').toggleClass('active');
$this.toggleClass('active');
//Hide All Panals
horizon.css('display','none');
aboutPanel.css('display','none');
photoPanel.css('display', 'none');
resumePanel.css('display', 'none');
//Show Correct Panel
switch($this.id){
case 'resumeBtn':
resumePanel.css('display', 'block');
break;
case 'portfolioBtn':
horizon.css('display','block');
break;
case 'photoBtn':
photoPanel.css('display','block');
arrange();
break;
case 'aboutBtn':
aboutPanel.css('display','block');
arrange();
$('#header .inner').animate({
width: '100%'
},600);
break;
}
notworkOn = false;
};
});