Menu in HTML, CSS, and JavaScript

Tiempo de lectura: 2 minutos

To create a horizontal menu with different options that change content based on the selected option, follow these steps.

First, create an unordered list (<ul>) representing your menu and give it some styles to remove bullets and set a dark background.

Each list item (<li>) represents a menu option and is floated left (float: left) to make them inline.

The links (<a>) inside each list item (<li>) are used as menu items and styled to have white text and a button-like style when hovered over (:hover).

Next, select all link elements (<a>) inside list items (<li>) in the enlaces variable as shown below:

var enlaces = document.querySelectorAll("ul li a");

Then, get the dynamic content element with the id “texto-contenido” in the contenidoDinamico variable:

var contenidoDinamico = document.getElementById("texto-contenido");

Add a click event handler for each link in the menu. When a link is clicked, it runs a function that does the following:

  • Removes the “selected” class from all links to deselect any previously selected link.
  • Adds the “selected” class to the currently selected link.
  • Gets the text of the selected link, representing the selected menu option.
  • Updates the dynamic content with a title (<h1>) displaying the selected option and a paragraph (<p>) with fictional content related to the option.
enlaces.forEach(function(enlace) {
    enlace.addEventListener("click", function() {
        // Remove the "selected" class from all links
        enlaces.forEach(function(enlace) {
            enlace.classList.remove("selected");
        });

        // Add the "selected" class to the clicked link
        this.classList.add("selected");

        // Get the text of the selected option
        var opcionSeleccionada = this.textContent;

        // Update the dynamic content based on the selected option
        contenidoDinamico.innerHTML = "<h1>" + opcionSeleccionada + "</h1><p>Content for " + opcionSeleccionada + "</p>";
    });
});

Finally, add a function called menuopciones that is triggered when the user scrolls the page (window.onscroll). This function adds or removes the “opcionselect” class from the menu depending on whether the user has scrolled far enough down the page. This is done to create a menu effect that sticks to the top when the user scrolls down.

window.onscroll = function() {
    menuopciones();
};

var menu = document.querySelector("ul");
var opcionselect = menu.offsetTop;

function menuopciones() {
    if (window.pageYOffset >= opcionselect) {
        menu.classList.add("opcionselect");
    } else {
        menu.classList.remove("opcionselect");
    }
}

Here’s the result and the complete example code.

Menu

This is an example of a simple menu created with HTML, CSS, and JavaScript for DevCodeLight.

Leave a Comment