Created
February 25, 2012 18:20
-
-
Save walterdavis/1909932 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.observe('dom:loaded',function(evt){ | |
//choose one type of tag that you only use for tabs (h2 here) | |
//within your .tabbed elements | |
var tabTag = 'h2'; | |
//common tab handler method | |
Element.addMethods({ | |
setTab: function(elm){ | |
//hide all the content | |
bodies.invoke('hide'); | |
//remove the active classname from the current tab | |
tabs.invoke('removeClassName','active'); | |
//set the current active tab and show its content | |
$(elm).addClassName('active').bodies.invoke('show'); | |
} | |
}); | |
//decorate all elements in the page that have the tabbed class | |
$$('.tabbed').each(function(tabarea){ | |
//set up a reference to all of the tabs, extend each tab with an | |
//expando property to hold a reference to the elements it controls | |
var tabs = tabarea.childElements().filter( | |
function(elm){ | |
return elm.match(tabTag); | |
}).each(function(elm){ | |
elm['bodies'] = $A(); | |
}); | |
//every top-level element in the container that isn't a tab | |
//must be content related to the previous tab | |
var bodies = tabarea.childElements().reject(function(t){ | |
return tabs.include(t); | |
}); | |
//common function to switch tabs | |
Element.addMethods({ | |
setTab: function(elm, evt){ | |
//hide all the content | |
bodies.invoke('hide'); | |
tabs.invoke('removeClassName','active'); | |
elm.addClassName('active').bodies.invoke('show'); | |
} | |
}) | |
//iterate over the body elements | |
bodies.each(function(elm){ | |
//get the tab for this body element | |
var tab = elm.previous(tabTag); | |
//hide the body element to begin with | |
elm.hide(); | |
//fill the tab's expando with a reference to this body element | |
tab.bodies.push(elm); | |
}); | |
//now, insert a structural element to hold the tabs | |
var tabholder = new Element('div', {'class': 'tabholder'}); | |
tabarea.insert({top: tabholder}); | |
//iterate over the tabs | |
tabs.each(function(tab){ | |
//move the tabs to their new home | |
tabholder.insert(tab.remove()); | |
//listen for clicks on each tab | |
tab.observe('click', function(){ this.setTab(); }); | |
//mark the first tab as active | |
}).first().setTab(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment