Today I needed to load a massive amount of text into dropped-down section on the page. And it was unlikely that users will expand that section, so no point in loading a huge load of data until it is needed. That is AJAX is for, isn’t it?

Here is the HTML for the Accordion:

<div class="accordion-ajax" data-url='/path/to/get/text/from'>
    <div class='accordion-head'>
       This is visible text to be presented for clicking
    </div>
    <div><!--This is required: it will be filled in with body of accordion when it is expanded--></div>
</div>

And here is the JavaScript code:

    $('.accordion-ajax').accordion({
        collapsible: true,
        active: false,
        clearStyle: true,
        autoHeight: false,
        header: '.accordion-head',          // point to the class that is used as a header
        heightStyle: 'content',
        icons: false,
        beforeActivate: function (event, ui) {
            var self = $(this); 

            // this bit is tricky. Make sure you have no empty space in the body of drop-down 
            if (ui.newPanel.html() == '') {         
                // taking data-url parameter from accordion header div
                // and load the returned contents into the accordion body.
                // presuming HTML is returned. 
                ui.newPanel.load(self.data('url'));
            }
        }
    }); 

See more details on API in jQuery Accordion API

  • Andy

    hi there, the first line of your javascript code references a class ‘accordion-ajax’ but this isn’t used in your sample html – so its an incomplete example and I’m confused as to exactly how to implement your solution! can you review and complete? thanks

    • You are correct, the solution was incomplete. I’ve updated the post with new html layout. And thanks for bringing this up: it is a very old post and can’t believe nobody mentioned this before.

      • Mehak

        where is that link. please mention the link..

        • Em.. this is link where you’d get the text to display. I can’t give it to you because it is up to you to decide where you take your text from.