How to make a menu on JavaScript

Create a fly-out menu using JavaScript & HTML: a step-by-step guide with an example.

Creating a JavaScript Menu

Creating a menu on JavaScript is a simple process. It requires the use of a few basic HTML elements, JavaScript code, and style sheets. The following example demonstrates how to create a menu in JavaScript.

Step 1: HTML Markup

The HTML markup used for the menu is quite simple. All that is required is an unordered list of menu items wrapped in a <div> element.

<div id="menu">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</div>

Step 2: JavaScript

The JavaScript code used to create the menu is quite simple. It consists of a function that creates the menu and attaches it to the page. The function takes two parameters - the list of menu items and the ID of the <div> element that will contain the menu.

function createMenu(items, containerId) {
  // Create the menu
  var container = document.getElementById(containerId);
  var menu = document.createElement('ul');
  for (var i = 0; i < items.length; i++) {
    var item = document.createElement('li');
    var link = document.createElement('a');
    link.href = items[i].href;
    link.innerHTML = items[i].name;
    item.appendChild(link);
    menu.appendChild(item);
  }
  container.appendChild(menu);
}

The function loops through the list of items and creates a link for each one. The links are then appended to the menu, which is then appended to the page.

Step 3: Call the Function

The final step is to call the function and pass it the list of menu items and the ID of the container element. The following example shows how to do this:

var items = [
  { name:'Home', href:'#' },
  { name:'About', href:'#' },
  { name:'Contact', href:'#' }
];
createMenu(items, 'menu');

The function is called and passed the list of items and the ID of the <div> element that will contain the menu. The menu is then created and added to the page.

Conclusion

Creating a menu in JavaScript is a simple process. All that is required is an unordered list of menu items, a few lines of JavaScript code, and a call to the function. Once the menu has been created, it can be styled with CSS to make it look however you want.

Answers (0)