toggleClass not keeping previous click event jquery
<p>I found a show/hide function <a href="https://stackoverflow.com/questions/38746844/condition-in-nextuntil-toggle-in-jquery/38763536#38763536">here</a> (not my work but similar my problem) and based on that I have created a fiddle demo (<a href="https://jsfiddle.net/q7sfeju9/" rel="nofollow noreferrer">https://jsfiddle.net/q7sfeju9/</a>), but it is not working correctly when clicking to show the rows. </p>

<p>In fiddle, if I hide the <code>Level 1.2</code> first, then <code>Level 1.1</code> and last <code>Level 1</code>, working fine. Now, if I click the <code>Level 1</code> again, it should show only the <code>Level 1.1</code> and <code>Level 1.2</code>, not there all sub level. But it is showing all levels and sub levels. If I hide any sub levels, I need those levels should hide until clicked. </p>

<p>Please someone can help me how can I do this.</p>

<p>Thanks in advance   </p>

<p>Update:</p>

<p>Please see the code below -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('tr').click(function(event) {
  event.stopPropagation();
  var currentLevel = parseInt($(this).attr('class')),
    state = $(this).hasClass('hiding'),
    nextEl = $(this).next(),
    nextLevel = parseInt(nextEl.attr('class'));
  while (currentLevel &lt; nextLevel) {
    nextEl.toggle(state);
    nextEl = nextEl.next();
    nextLevel = parseInt(nextEl.attr('class'));
  }
  $(this).toggleClass('hiding');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr[class^="2"] td {
  padding-left: 20px;
}

tr[class^="3"] td {
  padding-left: 40px;
}

tr[class^="4"] td {
  padding-left: 60px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="test"&gt;
  &lt;tr class="1"&gt;
    &lt;td&gt;Level 1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="2"&gt;
    &lt;td&gt;Level 1.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 1.1.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 1.1.2&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="2"&gt;
    &lt;td&gt;Level 1.2&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 1.2.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 1.2.2&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="4"&gt;
    &lt;td&gt;Level 1.2.2.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="4"&gt;
    &lt;td&gt;Level 1.2.2.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="1"&gt;
    &lt;td&gt;Level 2&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="2"&gt;
    &lt;td&gt;Level 2.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 2.1.1&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class="3"&gt;
    &lt;td&gt;Level 2.1.2&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;</code></pre>
</div>
</div>
</p>