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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
How to define visibility for a property in PHP?PHPHow to reprocess failed items in Etrieve Flow?MiscellaneousWordPress: How to setup and get values from an ACF options page?WordPressCreate a responsive pricing table using simple HTML and CSSCSSHow to get the height and width of an element using JavaScript?JavaScriptFETCH clause in PostgreSQLPostgresINTERSECT and EXCEPT in PostgresPostgresThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSHow to add Lifecycle Methods to a Class in React?ReactWordPress 5.7 is migrating to latest jQuery version and people are freaking outjQueryAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to check if a link has http or https in it in JavaScript?JavaScript