Friday, July 19, 2013

Toggle Panel for Twitter Bootstrap

I had searched for a toggle panel widget and obtained one that sort-of worked from: where-are-collapsible-panels-in-this-framework

It was designed for JQuery and my toggle icon kept appearing on a line by itself.  I'm a relative JQuery newbie but old enough to know that writing highly chained JQuery code is someone's way of ensuring job security.

I refactored the code to use variables, added comments and substituted bootstrap icons for JQuery icons.  Here is the revised widget:


$.fn.togglepanels = function() { return this.each(function() { $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset"); $h3 = $(this).find("h3"); $h3.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom"); // Add hover so this is apparent that it is a control $h3.hover(function() { $(this).toggleClass("ui-state-hover"); }); // Add the decorative icon $h3.prepend('<span class="toggle-panel-icon icon-plus-sign"></span>'); $h3.click(function() { $h3 = $(this); $h3.toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom"); $icons = $h3.children(".toggle-panel-icon"); $icons.toggleClass("icon-plus-sign icon-minus-sign"); // Stop any animations on content $content = $h3.next(); $content.stop(true, true); // Show/hide using a sliding animation $content.slideToggle(); return false; }); // Add styling classes to the content and initial hide it $content = $h3.next(); $content.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); $content.hide(); // Content is returned by default }); };

No comments:

Post a Comment