Skip to content

Instantly share code, notes, and snippets.

@pichfl
Created January 29, 2012 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pichfl/1699937 to your computer and use it in GitHub Desktop.
Save pichfl/1699937 to your computer and use it in GitHub Desktop.
Super basic tabs with JavaScript: click/touch adds a class to the clicked element and to the element with the id of the clicked elements href.
(function(w,d) {
var q = 'querySelectorAll',
navs = d[q]('nav a'), // Tabs
pages = d[q]('section'), // Contents
a = 'active', // ClassName
cn="className",
aC=function(c,b){if(c.classList){c.classList.add(b)}else{var d=" ";var a=(d)?(d+c[cn]+d).indexOf(d+b+d)>-1:String(this).indexOf(b)>-1;if(!a){c[cn]=(c[cn]+" "+b)}}},
rC=function(b,a){if(b.classList){b.classList.remove(a)}else{b[cn]=b[cn].replace(new RegExp("(^|\\s)"+a+"(?:\\s|$)"),"$1")}};
for (var i=0; i < navs.length; i++) {
navs[i].savedPage = d[q](navs[i].href.match(/#.*$/)[0])[0];
navs[i].addEventListener(('ontouchstart' in w)?'touchstart':'click', function(event) {
event.preventDefault();
for (var i=0; i < navs.length; i++) {
rC(navs[i],a);
rC(pages[i],a);
}
aC(this,a);
aC(this.savedPage,a);
});
};
}(window,document));
nav a{ color: #000 }
nav a.active{ color: #f00; }
section{ display: none; }
section.active{ display: block; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment