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 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS? #Jan 8 How to Install Xcode Command Line Tools on MacOS?
You might also like these
Add animated hamburgers menu using Hamburgers collection on GitHubCSSHow to Make CSS Lists Bullets Smaller?CSSFive common features of Angular template syntax (with examples)AngularSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)MiscellaneousSome interesting HTML Input Attributes to rememberHTMLSome SQL LIKE Operators We Need to Keep in MindSQL/MySQLHow does while loop work in SCSS?SCSSCROSS JOIN in PostgresPostgresHow to update database configurations in WordPress?WordPressPre-defined DatePipe format options in Angular 9AngularHow to disable the Recovery Mode in WordPress?WordPressSolution to “NullInjectorError: No provider for module” in Angular 9Angular