Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon clicking?

An example of this functionality can be seen on this website:

If you're wondering how to achieve this effect using CSS and JS, take a look at the code snippet below:

 <ul class="navigation clearfix">   
        <li class="active">
            <a href="#">HOME</a>
        </li>

        <li>
            <a href="#">pages</a>
            <ul class="drop-down">
                <li>
                    <a href="event.html">Event</a>
                </li>
                <li>
                    <a href="blog.html">Blog</a>
                </li>
                <li>
                    <a href="blog-detail-page.html">Blog-Detail</a>
                </li>
                <li>
                    <a href="travel-info.html">Travel-Info</a>
                </li>
                <li>
                    <a href="404-page.html">404</a>
                </li>
            </ul>
        </li>
    </ul>

To style your navigation menu accordingly, here's an example of some CSS:

 .clearfix {
     display: block;
  }
  ul {
      list-style-type: none;
  }
  ul, ol {
     font-size: 100%;
     line-height: 1.5;
     list-style: none;
  } 
 .navigation > li {
    padding: 16px 0px 36px 26px;
    float: left;
    position: relative;
    line-height: 1.5em;
}
.navigation > li:hover .drop-down {
    top: 76px;
    left: auto;
    left: 16px;
    right: 0;
}
.drop-down {
    position: absolute;
    top: 100px;
    width: 160px;
    z-index: 999;
    left: -9999px;
    opacity: 0;
    transition: top .2s ease, opacity .2s ease;
}   

Answer №1

If you want to create a dropdown menu that opens on hover, you can add a class like .open to your li element using the mouseenter event.

Here is an example of how you can achieve this:

var dropdown = $(".is-dropdown");

dropdown
  .on("mouseenter", function() {
    $(this)
      .addClass("open");
  })
  .on("click", function() {
    $(this).removeClass("open");
  }); 

Check out this jsFiddle for a demonstration.


CODE SNIPPET:

var dropdown = $(".is-dropdown");

dropdown
  .on("mouseenter", function() {
    $(this)
      .addClass("open");
  })
  .on("click", function() {
    $(this).removeClass("open");
  });
.clearfix {
  display: block;
}
ul {
  list-style-type: none;
}
ul,
ol {
  font-size: 100%;
  line-height: 1.5;
  list-styles: none;
}
.navigation > li {
  padding: 16px 0px 36px 26px;
  float: left;
  position: relative;
  line-height: 1.5em;
}
.drop-down {
  position: absolute;
  top: 100px;
  width: 160px;
  z-index: 999;
  left: -9999px;
  opacity: 0;
  transition: top .2s ease, opacity .2s ease;
}
.navigation > .open .drop-down {
  top: 76px;
  left: auto;
  left: 16px;
  right: 0;
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigation clearfix">
  <li class="active">
    <a href="#">HOME</a>
  </li>

  <li class="is-dropdown">
    <a href="#">pages</a>
    <ul class="drop-down">
      <li>
        <a href="event.html">Event</a>
      </li>
      <li>
        <a href="blog.html">Blog</a>
      </li>
      <li>
        <a href="blog-detail-page.htmm">Blog-Detail</a>
      </li>
      <li>
        <a href="travel-info.html">Travel-Info</a>
      </li>
      <li>
        <a href="404-page.html">404</a>
      </li>
    </ul>
  </li>
</ul>

Answer №2

While there may be additional factors at play in this feature, I have provided a basic solution for you.

$(document).ready(function() {
  $('.drop-down').slideUp(0); //hides all drop-down menus  


  $('.navigation li:has(> ul.drop-down)').on('mouseenter', function() {
    $(this).children('ul').slideDown();
  });


  $('.closeEm').on('click', function(e) {
    e.preventDefault(); // prevent the page from jumping on click
    $('ul.drop-down').slideUp();
  });


});
.clearfix {
  display: block;
}
ul {
  list-style-type: none;
}
ul,
ol {
  font-size: 100%;
  line-height: 1.5;
  list-style: none;
}
.navigation > li {
  padding: 16px 0px 36px 26px;
  float: left;
  position: relative;
  line-height: 1.5em;
}
.navigation li {
  background-color: #ddd;
}
.drop-down {
  position: absolute;
  top: 70px;
  width: 160px;
  z-index: 999;
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigation clearfix">
  <li class="active">
    <a href="#">HOME</a>
  </li>

  <li>
    <a href="#">pages</a>
    <ul class="drop-down">
      <li>
        <a href="event.html">Event</a>
      </li>
      <li>
        <a href="blog.html">Blog</a>
      </li>
      <li>
        <a href="blog-detail-page.html">Blog-Detail</a>
      </li>
      <li>
        <a href="travel-info.html">Travel-Info</a>
      </li>
      <li>
        <a href="404-page.html">404</a>
      </li>
    </ul>
  </li>


  <li>
    <a href="#">pages</a>

  </li>


  <li>
    <a href="#">pages</a>

  </li>


  <li>
    <a href="#">pages</a>

    <li>
      <a href="#" class="closeEm">Close Dropdowns</a>
    </li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

Using jQuery to insert a new string into the .css file

I'm currently working on a jQuery function to make my font size responsive to changes in width. While I am aware of other options like Media Query, I prefer a solution that offers smoother transitions. Using vw or vh units is not the approach I want t ...

How can I use lodash to iterate through and remove whitespace from array elements?

I am currently working on a project involving demo lodash functionality, and I have encountered some unexpected behavior. Within an array of cars, there are various non-string elements mixed in. My goal is to iterate through each element of the array, rem ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

HTML/JavaScript: Embrace the Power of Dynamic Page

I have a unique element in my HTML code: <image src="http://..." style='...'> Using Python-Flask, I pass on a dynamic source address and save it as window.dynamicEmbedding. Now, during page load, I want to change the image's ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

Ways to prevent the corruption of a URL?

I have a method that calls a controller function from a script with arguments like this: $("#export-it-Voip").attr("href", '@Url.Action("ExportAllToExcel", "Home")?strvoicerecordfetchquery=' + voipquery + '&nSelectAllten=' + 10+&ap ...

Checkbox remains selected even after the list has been updated

I am currently dealing with an array of objects where each object has a property called "checked." When I click on a checkbox, it becomes checked. However, when I switch to another list, the checkmark remains even though it should not. Here's an examp ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

What are some ways to showcase information using AJAX?

Hey there! I'm currently facing an issue with AJAX. I need help in extracting data and displaying it as a table in HTML format. The data I have is just dummy, but in reality, it consists of multiple objects, including nested ones. Can someone please a ...

Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser. Here is my current code: var htt ...

What could be causing the error message "Error: Cannot modify headers after they are sent" to appear?

I am attempting to insert data into an MS SQL server when a JSON Data API POST request is made. var express = require('express'); var app = express(); var sql = require('mssql'); // Connection string parameters. var sqlConfig = { u ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Navigation Menu Dropdown Present on the Right Side and Arranged in a Horizontal Stack

I'm having trouble with a dropdown menu in my navigation bar. I followed the example on W3Schools but when I hover, the menu appears horizontally instead of vertically and to the far right of the page. I've searched for solutions but can't s ...

What is the best way to transfer static assets from an npm package to a nuxt project?

Has anyone successfully sent assets from an npm package to a nuxt application before? I have a vue component within an npm package with the following structure: -src/ -assets/ -noun-filter.svg In this npm package, the vector image is included in the v ...

Best Practices for Integrating PHP Code into an HTML File for Contact Form Placement

My current setup involves an html file named index.html, which contains the code for my contact form fields such as name and email. Is there a way to include PHP code in this file without converting it to index.php? ...

Customizing the color of buttons in MUI 4

Currently, I am utilizing mui V4 for my styling and attempting to incorporate an additional color for my buttons. I understand that it only accepts these predefined colors: expected one of ["default", "inherit", "primary", "secondary"]. To achieve this, I ...

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...