espenhogbakk
espenhogbakk

Reputation: 11728

Add items to a jQuery Accordion with jquery

I am using the jQuery accordion plugin to make an accordion of some data. Then I want the user to be able to add more data to the accordian. I have setup the accordion to function properly, then I've made a function that prepends a "list item" to the accordion that matches the accordion semantics.

Is it possible to "update" the accordion so that it works with the newly added element, without saving the new data to database and refreshing the page?

Something like this:

.accordion('refresh')

Or something like the live event added in jQuery 1.3, anybody got a clue?

Upvotes: 46

Views: 40836

Answers (5)

Jimmy Stenke
Jimmy Stenke

Reputation: 11220

I haven't tested it, but this should probably work: Say that you have your accordion with id #accordion

$('#accordion').append('<h3><a href="#">New Paragraph</a></h3><div><p>New data</p></div>')
    .accordion('destroy').accordion();

Basically, just destroy and re-create the accordion.

UPDATE:

Since this answer was written a refresh() method has been added to the accordion widget. It can be invoked by calling:

$( ".selector" ).accordion( "refresh" );

You can read more about this method here

Upvotes: 100

Mark D.
Mark D.

Reputation: 96

As mentioned above by Shahzad, jQuery UI 1.10 has made this easier; see the documentation.

Upvotes: 6

Tak0r
Tak0r

Reputation: 31

Since i needed a working add/edit/delete vor accordion items i hacked this little javascript functions for this purpose

http://jsfiddle.net/Sd6fC/

h3 and div need an unique id which goes by the following convention

<h3 id="divname_hitm_<uniquenumber>"><h3>

the corresponding div need the following

<div id="divname_ditm_<samenumber as h3"></div>

sample accordion code block

<div id="divname">
    <h3 id="divname_hitm_1><a href="#">Section 1</h3>
    <div id="divname_ditm_1>
        <p>Section 1 Payload</p>
    </div>
    <h3 id="divname_hitm_2><a href="#">Section 2</h3>
    <div id="divname_ditm_2>
        <p>Section 2 Payload</p>
    </div>
</div>

have fun maybe it helps some ppl out there!

Upvotes: 0

Wesley
Wesley

Reputation: 2264

To add a new section, and keep the old one active:

var active = $('#accordion').accordion('option', 'active');
$('#accordion').append('<h3><a href="#">New Paragraph</a></h3><div><p>New data</p></div>')
    .accordion('destroy').accordion({ active: active});

Upvotes: 8

jfrobishow
jfrobishow

Reputation: 2895

You might want to look at the LiveQuery plugin: http://plugins.jquery.com/project/livequery

It allows you to add events and binding after the DOM is loaded.

Upvotes: 0

Related Questions