1

I want to create a simple dropdown menu when a user clicks on an image. Currently I'm using CSS hover but it doesn't stay so I want to convert it to a JS onClick function.

<html>
<head>
<style>
ul {
text-align: left;
display: inline;
margin: 0;
list-style: none;
}
ul li {
display: inline-block;
position: relative;
}
ul li ul {
padding: 0;
position: absolute;
display: none;
opacity: 0;
visibility: hidden;
}
ul li ul li { 
display: block;  
}
ul li:hover ul {
display: block;
opacity: 1;
visibility: visible;
}
</style></head><body>
<ul>
<li>
<img src="https://cdn1.iconfinder.com/data/icons/thincons/100/menu-128.png" width="20px;" height="18px;"/>
<ul class="lang">
<li>Web Design</li>
<li>Web Development</li>
<li>Illustrations</li>
</ul>
</li>
</ul>

</body>  
</html>

1 Answer 1

2

With a little jQuery, we can easily toggle a class on or off to represent 'showing' the menu:

$("#menu").click(function(){
    $(this).toggleClass("activated");
});

And changing the CSS (instead of :hover) to:

ul li.activated ul {
    display: block;
    opacity: 1;
   visibility: visible;
}

The HTML only needs that first li element to have an id, which lets us use jQuery to bind a click event to it.

<ul>
<li id="menu">

You can see it all in action on this fiddle.

Edit: For a non-jQuery solution, you can use the following Javascript code:

var myEl = document.getElementById('menu');
myEl.addEventListener('click', function() {
    this.classList.toggle('activated');
}, false);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks brotha, you da best. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.