Yogesh Chauhan's Blog

How to create a simple drop down menu using JavaScript and CSS?

in CSS & JavaScript on March 17, 2021

Creating a drop down menu has one simple logic. Show the drop down box when clicked(hovered) on parent element. There are multiple ways to do that, even using just CSS. But in this example I am gonna use few lines of JavaScript to capture the onclick event.

Let’s start with simple HTML and create the container with a button to click on.

Now, let’s add the style for that button and the container. We’ll keep the position of the container relative.

Let’s add the menu items container inside the main container.

Now, let’s add style for that menu container. We need to keep the position absolute. I have kept the menu items style same as the button but feel free to modify it.

Now, the only thing left to do is adding a class and toggle it using JavaScript onclick event.

Let’s add just few lines of JavaScript code and the CSS class as well.

Here’s the full code and demo:


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Slider animation using CSS transform propertyCSSPostgreSQL BETWEENPostgresHow to add and remove capabilities from a role in WordPress?WordPressHow to convert a function component into a class in React?ReactWhat is the best way to add JavaScript Code into HTML?HTMLThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSCreate a simple bar chart and column chart using pure CSS gridCSSHow to clean up after a plugin uninstall in WordPress?WordPressWhat is PostgreSQL? How similar or different it is from SQL?PostgresHow to create a secure random number using JavaScript?JavaScriptthe box-sizing property in CSSCSS4 different ways to create JavaScript ObjectsJavaScript