Sunday 18 November 2012

Switch between Tabs and Accordion

Working with jQuery UI sometimes I've hesitated between using an accordion widget or a tabs widget to lay out some data. In both cases the information to be displayed consists of headers and contents, so though the html tags expected by jquery UI to create tabs or accordions are different, it should be pretty simple to switch from one to another.

The idea is to have an object holding a reference to a container DOM element and to a list of headers/contents items, and exposing 2 methods, one for creating a Tab and one for creating an Accordion. You'll use it like this:

var books = [
 {
  name: "First Book",
  text: "

this is the first

" + "
  • aa
  • bb
" }, { name: "Second Book", text: "this is the second" }, { name: "Third Book", text: "this is the third" }, ]; $(document).ready(function(){ var myTabsAccordion = new animatedTabsAccordion("#booksContainer", books); $("#accordionBt").click(function(){ myTabsAccordion.generateAccordion(); }); $("#tabsBt").click(function(){ myTabsAccordion.generateTabs(); }); });

We can do it a bit more nicely looking if we show/hide the widgets using some kind of animation. I had already developed some months ago an animator to show an accordion in an animated way. I've added a hiding animation and expanded it for being used with tabs

You can see the animations on its own here and the animated tabs-accordion here

I've uploaded the final result to GitHub, so you can check the code there.

http://www.telecable.es/personales/covam1/deployToNenyures/SourceCode/jQuery/tabsAccordionStuff/samples/tabsAccordionTest.html

No comments:

Post a Comment