2

I use Nestable plugin to create tree structure. I want to toggleable button to expand/collapse.

To expand I add this:

$('#tree').nestable('expandAll');

To collapse I add this:

$('#tree').nestable('collapseAll');

But I did it separately with 2 different buttons. How to toggle expand/collapse behavior by one button?

html:

<div id="tree" class="dd">
    <ol class="dd-list">
        <li class="dd-item" data-id="1">
            <div class="dd-handle">Item 1</div>
        </li>
        <li class="dd-item" data-id="2">
            <div class="dd-handle">Item 2</div>
        </li>
        <li class="dd-item" data-id="3">
            <div class="dd-handle">Item 3</div>
            <ol class="dd-list">
                <li class="dd-item" data-id="4">
                    <div class="dd-handle">Item 4</div>
                </li>
                <li class="dd-item" data-id="5">
                    <div class="dd-handle">Item 5</div>
                </li>
            </ol>
        </li>
    </ol>
</div>
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

3 Answers3

2

Toggle between two function like this:

var click = false;
  function callFunction(el) {
    if (!click) {
     //$('#tree').nestable('expandAll');
     console.log('expandAll');
      click = true;
    } else {
      //$('#tree').nestable('collapseAll');
      click = false;
      console.log('collapseAll');
    }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="callFunction(this)">Toggle</button>
Pedram
  • 15,766
  • 10
  • 44
  • 73
1

you can add an event to the button which will check the action of the button

   $('#tree').on('click', 'button', function(e){
    $(e.target).data('action') == 'expand-all' ? $(e.target).data('action', 'collapse-all') : $(e.target).data('action', 'expand-all')
})
0

try to use

$('#tree').nestable();

as it toggle automatically

here is the link i tried https://codepen.io/anon/pen/goxpKv