How to load content in jQueryUI accordion dynamically


Hey guys,

Do you aware of the fact that jQuery UI allows to load content dynamically for tabs but not for accordion?. So here I came up with a simple solution. You just have to pass a url in href attribute for each accordion header as shown below:

<div id="accordion">
	<h3><a href="ajax1.html">Section 1</a>>/h3>
	<div>
		<p>
		  Loading... Please wait.
		</p>
	</div>
	<h3><a href="ajax2.html">Section 2</a></h3>
	<div>
		<p>
		  Loading... Please wait.
		</p>
	</div>
</div>

Accordion UI provides many callback functions but we are going to use one of them, the most important callback function,  activate which gets called when you click on any accordion panel to open it. We are going to use it to load content using AJAX.

<script>
  $(function() {
     $( "#accordion" ).accordion({
        collapsible: true,
        active : false,
        activate: function (e, ui) {
          $url = $(ui.newHeader[0]).children('a').attr('href');
	  $.get($url, function (data) {
	     $(ui.newHeader[0]).next().html(data);
          });
        }
     });
  });
</script>

You can also download the code from github. Happy Coding 🙂

Advertisements

9 thoughts on “How to load content in jQueryUI accordion dynamically

  1. Nice. But I am looking for more. So this works great the first time. The second time a user tries to open the accordion though, I should not need to reload the content, it just stays on to save a lot of traffic and waiting. Do you have a way for that? Actually I think I can just check if some contents exists?

    • Oops, I’ve replaced the hotlinked jquery/jqueryui. And also the API has also changed which does not support `change` event. Its replaced by `activate` now. Thanks for informing me. Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s