Tuesday, November 26, 2013

jQuery UI: Remote Accordion Content

The jQuery UI tabs widget supports loading tab content from remote sources out of the box. The accordion widget, however, does not. Which is unfortunate because there are advantages to deferring the loading of content till the section is expanded. Your application may have an accordion for several seldom, if ever, sections that are opening. That's a big cost savings, so let's see how we can implement such a capability.

We'll use mockjax to simulate our two server resources — basic HTML content that we would like loaded into our accordion widget on demand. As this demonstration shows, the only addition code needed are create and activate event handlers for the accordion instance. Additionally, we have to tell the accordion where to find our remote content for a given section, once it's expanded. Let's have a look at these two functions, and how they use the content option we're passing to the widget.

create: function( e, ui ) {
                
    var $this = $( this ),
        active = $this.accordion( "option", "active" ),
        content = $this.accordion( "option", "content" );
                
        if ( active !== false ) {
            ui.content.load( content[ active ] );
        }
            
}

The create event is triggered when the accordion is first instantiated. It's here that we'll want to load the content for the initially expanded section. The active variable is the index of the currently active section. The content variable is an array of URLs that map to the accordion indices. Note, we have to make sure that active isn't false — a valid value. If it isn't, we load the content into ui.content — the active panel.

activate: function( e, ui ) {
            
    var $this = $( this ),
        active = $this.accordion( "option", "active" ),
        content = $this.accordion( "option", "content" );
                
    ui.newPanel.load( content[ active ] );
    ui.oldPanel.html( $( "<p/>" ).text( "Loading..." ) );
            
}

The activate handler is similar to the create handler. The difference being, it loads content into ui.newPanel, and resets the content of ui.oldPanel.

No comments :

Post a Comment