Tuesday, March 4, 2014

Custom Accordion Header Icons

The jQuery UI accordion widget has an icons option that let's the developer change the defaults. The defaults use the ui-icon-triangle-1-e icon for the collapsed state, and the ui-icon-triangle-1-s icon for the expanded state. These are classes taken from the theme framework, and so the fundamental limitation is that you have to use an icon that's already there. Either that, or extend the available icons available to your theme. The latter option is painful if all you want to do is use an accordion header icon specific to the content found in that section.

Luckily, there's a short-cut that works well for me. It disables the accordion icons altogether, and adds in the custom icon via CSS. Mind you, this solution doesn't change based on the collapsed versus expanded state, but that's not always important. For example, here's what my custom icons look like in the collapsed state.

An here's what they look like when expanded.

To turn off the accordion icons, the code to create the widget looks like this. The icons option is set to false, which hides the icons completely.

$( "#accordion" ).accordion({
    icons: false

With the default icons out of the way, we can implement the necessary CSS classes used to add the custom icons to the header. Here's what that CSS looks like.

#accordion .jquery {
    background-image: url('myicon.ico')

#accordion .jqueryui {
    background-image: url('myicon.ico');

#accordion .header-icon {
    background-repeat: no-repeat;
    background-position: 0.5em;
    padding-left: 2em;    

The first two classes set the background-image property to the image we want used as the header icon. The header-icon class is used to position the icon to the left of the header, and slide the header text slightly to the right, to make room. Now these classes can be applied to each h3 element of the accordion to set the custom icon.

No comments :

Post a Comment