dynamic php menu with hidden sub-categories only showing when the category name is clicked

Question

This is for a wordpress store and I want to show the categories names automatically, but with the sub-categories hidden, the code below works perfectly with the hover effect, now I wish to have the click effect instead. The $cats variable is to use the get_terms() function, but for here to work everywhere I had included a few categories, the categories only go so far as the "third generation".

<?php $cats = array(array('first', 'sub-first', 'sub-sub-first'),
                    array('second', 'sub-second'),
                    array('third', 'sub-third', 'sub-sub-third')); ?>
<h3>Categories</h1>
<ul class="ul1"> <?php
  foreach($cats as $cat):
    if (isset($cat[0])): ?>
      <li class="li1" onclick="test()"><a href="#"><?php echo $cat[0] ?></a> <?php
        if (isset($cat[1])):?>
          <ul class="ul2">
            <li class="li2"><a href="#"><?php echo $cat[1] ?></a> <?php
              if (isset($cat[2])):?>
                <ul class="ul3">
                  <li class="li3"><a href="#"><?php echo $cat[2] ?></a> </li>
                </ul> <?php
              endif; ?>
            </li>
          </ul> <?php
        endif; ?>
      </li> <?php
    endif;
  endforeach; ?>
</ul>

<style media="screen">
  ul{
    list-style: none;
  }
  a{
    text-decoration: none;
    color:#fff;
  }
  a:hover{
    color:#EF7522;
  }
  .li1{
    background:#1B2332;
    width:200px;
    border:1px solid lightgreen;
    padding:10px;
  }
  .ul2, .ul3{
    display:none;
  }
  .li1:hover .ul2{
    display:block;
  }
  .ul2:hover .ul3{
    display:block;
  }
</style>

for the click effect I had remove from the style the last two hover effects and add the javascript function test();

<script type="text/javascript">
    function test(){
        $(".ul2").css({
            "display":"block"
        });
    } 
</script>

What is happening is that I click a category and all sub-categories are showing, What I wanted is the same as the hover effect, that if I click the first category, I have only the sub-categories of that category and so on.

If someone could help me, I have been twisting my mind over this for a few days already!

0
tlago calado 2 months 0 Answers 16 views 0

Leave an answer