$(document).ready(function() { // go for the good old toggling //make it reusable by abstracting the header click element var list_header = $('h4'); var open_header = $('#'+location.href.split('#')[1]); //initially hide the element directly after the h4 list_header.next().hide(); open_header.next().show(); //append the click events for individual open/closing list_header.click(function() { toggleElement(this); }); //go for the open/close all $('.open_all').click(function (e) { //prevent the default link behavior, not needed if img is used e.preventDefault(); //for each list element call toggle function open_all(list_header); }); //go for the close all $('.close_all').click(function (e) { //prevent the default link behavior, not needed if img is used e.preventDefault(); //for each list element call toggle function close_all(list_header); }); //end toggling }); /** * utility function to toggle elements * detects wether an elements is visible and if so closes it * the opening goes the other way round * @param String - a dome element h3.myClass / #myId / .. */ function toggleElement(el) { if($(el).next().is(':visible')) {//already open, close it hideElement(el); } else {//closed .. so open it close_all('h4') showElement(el); } } function close_all(el) { $(el).each(function(){ if($(this).next().is(':visible')) { hideElement(this); } }); } function open_all(el) { $(el).each(function(){ if($(this).next().is(':hidden')) { showElement(this); } }); } /** * shows the element next/after to the given element * adds a class "open" to the element */ function showElement(el) { $(el).next().slideDown('slow'); $(el).addClass('open'); } /** * hides the element next/after to the given element * removes open class from element */ function hideElement (el) { $(el).next().slideUp('slow'); $(el).removeClass('open'); }