HTML Element Style How to - Click image to toggle UL items








Question

We would like to know how to click image to toggle UL items.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.menu {<!--from  ww w.  j a v  a 2 s. co  m-->
  margin-left: 5px;
  color: #C00;
  list-style-type: none;
}

.submenu {
  margin-left: 10px;
  color: #C90;
  list-style-type: none;
  border: thin solid #00F;
}

.hidden {
  display: none;
  color: #444;
}

.menu a {
  font-style: normal;
  text-decoration: none;
  color: #C00;
}
</style>
<script type='text/javascript'>

if (document.addEventListener)
    document.addEventListener("DOMContentLoaded", function(){

    var img = document.getElementsByTagName( 'img' )[0];
    img.onclick = function () {
        var submenu = this.parentNode.getElementsByTagName( 'ul' )[0];
        if ( this.alt === '+' ) {
            this.alt = '-';
           // this.src = 'images/minus.gif';
            submenu.className = 'submenu';
        } else {
            this.alt = '+';
          //  this.src = 'images/plus.gif';
            submenu.className = 'hidden';
        }
    };
    }, false);

</script>
</head>
<body>
  <ul class="menu">
    <li><img src="" alt="+"> <a href="#">Menu Item 1</a>
      <ul class="hidden">
        <li><a href="#">submenu item 11</a></li>
        <li><a href="#">submenu item 12</a></li>
      </ul>
    </li>
  </ul>
</body>
</html>

The code above is rendered as follows: