Skip to content Skip to sidebar Skip to footer

How To Show An Ul When A Particular Li Is Clicked Using Jquery?

I want to show the ul class of li which is clicked. My html is:

Solution 1:

For you to achieve this, you will have to take advantage of location hash. Do the following :

  1. On your anchor tags, that toggle your ul, add href to a dummy unique value. Make sure the value is same as the id of the li you are in.
<ul class="level0">
      <li class="level1" id="li1">
          <a href="#li1">Toggle.1</a>
          <ul class="level1" style="display:none;">
  1. When ever page loads, read window location hash.

var li = window.location.hash;

  1. If hash is found, show the related ul.
if(li!=""){
  $(li + " ul").show();
}

This way you will be able to show the last opened ul by the user.

$(function() {
  var li = window.location.hash;
  if (li != "") {
    $(li + " ul").show();
  }
  $('li.level1 a').click(function() {
    $(this).parent().siblings().each(function() {
      $(this).find("ul.level1").hide();
    });
    $(this).siblings("ul.level1").show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="level0">
  <li class="level1" id="li1">
    <a href="#li1">Toggle.1</a>
    <ul class="level1" style="display:none;">
      <li class="level2"><a href="#">Level2.1</a>
      </li>
      <li class="level2"><a href="#">Level2.1</a>
      </li>
      <li class="level2"><a href="#">Level2.1</a>
      </li>
    </ul>
  </li>
  <li class="level1" id="li2">
    <a href="#li2">Toggle.2</a>
    <ul class="level1" style="display:none;">
      <li class="level2"><a href="#">Level2.2</a>
      </li>
      <li class="level2"><a href="#">Level2.2</a>
      </li>
      <li class="level2"><a href="#">Level2.2</a>
      </li>
    </ul>
  </li>
  <li class="level1" id="li3">
    <a href="#li3">Toggle.3</a>
    <ul class="level1" style="display:none;">
      <li class="level2"><a href="#">Level2.3</a>
      </li>
      <li class="level2"><a href="#">Level2.3</a>
      </li>
      <li class="level2"><a href="#">Level2.3</a>
      </li>
    </ul>
  </li>
</ul>

Post a Comment for "How To Show An Ul When A Particular Li Is Clicked Using Jquery?"