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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #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

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPHow to Make a Simple Module with a Form and Menu Link in Drupal 7.x?DrupalHow Routing works in Angular?AngularHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSSHow to remove WordPress TinyMCE Editor buttons?WordPressArray destructuring and Object destructuring in JavaScriptJavaScriptHow to install Gulp with WordPress?WordPressHow to animate list items using CSS and JavaScript?CSSHow to change CSS with JavaScript?CSSRecursion in JavaScriptJavaScriptRecursive WITH Queries in Postgres (Common Table Expressions)PostgresWhat’s the difference between visibility: hidden and display: none?CSS