jquery-ui accordion - How to dynamically create a new section
Asked Answered
A

1

5

I want to know whether there exists a method that I could add a new section using jQuery UI

This is what I do so far without any error, but the accordion don't work since I add a new one

$( function() {
    $( "#accordion" ).accordion();

    $('#addNewSection').on('click', function() {
        var newH3 = document.createElement('h3');
        var newDiv = document.createElement('div');
        var acc = document.getElementById('accordion');
        var number = document.getElementsByTagName('h3').length;

        newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This won't collapse)";
        newDiv.innerText = 'This is a new section after clicking the button';
        acc.appendChild(newH3);
        acc.appendChild(newDiv);
    });
} );
h3 { background-color: "blue"; }
div { background-color: "lightgreen"; }
<div id="accordion">
    <h3>Section 1 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 1
        </p>
    </div>

    <h3>Section 2 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 2
        </p>
    </div>
</div>
<button id="addNewSection">AddOne</button>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

How to fix it? Or is there any official method I can use?

Asco answered 3/1, 2018 at 10:11 Comment(0)
T
7

You can use refresh method of accordion at the end of your click event (Documentation) :

$( function() {
    $( "#accordion" ).accordion();

    $('#addNewSection').on('click', function() {
        var newH3 = document.createElement('h3');
        var newDiv = document.createElement('div');
        var acc = document.getElementById('accordion');
        var number = document.getElementsByTagName('h3').length;

        newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This WILL collapse)";
        newDiv.innerText = 'This is a new section after clicking the button';
        acc.appendChild(newH3);
        acc.appendChild(newDiv);
       $( "#accordion" ).accordion("refresh");
    });
} );
h3 { background-color: "blue"; }
div { background-color: "lightgreen"; }
<div id="accordion">
    <h3>Section 1 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 1
        </p>
    </div>

    <h3>Section 2 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 2
        </p>
    </div>
</div>
<button id="addNewSection">AddOne</button>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Tenorrhaphy answered 3/1, 2018 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.