N. A. N. A. - 6 months ago 46
HTML Question

External Button to open/close Accordion

I need help to open or close accordion with extra buttons.

Here is example of the accordion with buttons:



$(function() {
$( "#tab1" ).accordion({
collapsible: true, active: false, heightStyle: "content"
});
$( "#tab2" ).accordion({
collapsible: true, active: false, heightStyle: "content"
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

<div id="tab1">
<h3>Tab 1</h3>
<div>1234567890 Text</div>
</div>
<div id="tab2">
<h3>Tab 2</h3>
<div>1234567890 Text 2</div>
</div>
<button><span>Open/Close Tab1</span></button>
<button><span>Open/Close Tab2</span></button>





Thank you for your help!

Answer

You can trigger the click event manually:

$(function() {
    $( "#tab1" ).accordion({
        collapsible: true, active: false, heightStyle: "content"
    });
    $( "#tab2" ).accordion({
        collapsible: true, active: false, heightStyle: "content"
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

<div id="tab1">
    <h3>Tab 1</h3>
    <div>1234567890 Text</div>
</div>
<div id="tab2">   
    <h3>Tab 2</h3>
    <div>1234567890 Text 2</div>
</div>
<button><span>Open/Close Tab1</span></button>
<button><span>Open/Close Tab2</span></button>
<script>
$('button').first().click(function(){
$('h3').first().click();
});
$('button').last().click(function(){
$('h3').last().click();
});
</script>