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.
<ulclass="level0"><liclass="level1"id="li1"><ahref="#li1">Toggle.1</a><ulclass="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();
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ulclass="level0"><liclass="level1"id="li1"><ahref="#li1">Toggle.1</a><ulclass="level1"style="display:none;"><liclass="level2"><ahref="#">Level2.1</a></li><liclass="level2"><ahref="#">Level2.1</a></li><liclass="level2"><ahref="#">Level2.1</a></li></ul></li><liclass="level1"id="li2"><ahref="#li2">Toggle.2</a><ulclass="level1"style="display:none;"><liclass="level2"><ahref="#">Level2.2</a></li><liclass="level2"><ahref="#">Level2.2</a></li><liclass="level2"><ahref="#">Level2.2</a></li></ul></li><liclass="level1"id="li3"><ahref="#li3">Toggle.3</a><ulclass="level1"style="display:none;"><liclass="level2"><ahref="#">Level2.3</a></li><liclass="level2"><ahref="#">Level2.3</a></li><liclass="level2"><ahref="#">Level2.3</a></li></ul></li></ul>

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