What is the best way to create this menu using a CSS pseudo-class selector?

I have created a menu and now I want to enhance its functionality by adding keyboard support. My goal is to make the menu accessible using keyboard keys, such as pressing Enter to show the menu, Tab to navigate through menu items, and ESC to hide the menu.

How can I modify my CSS to achieve this?

HTML

<ul class="hMenu">
  <li><a href="">prod1</a>
    <div>
      <a href="">test1</a>
      <a href="">test2</a>
      <a href="">test3</a>                  
    </div>
  </li>
  <li><a href="javascript:void(0);" >prod2</a>
    <div>
      <a href="">test4</a>  
      <a href="">test5</a>                  
    </div>
  </li>  
</ul>

CSS

ul.hMenu li:hover a {
  color:red;
}           
ul.hMenu  { 
  margin: 0;
  padding: 0; 
  z-index: 1;               
}
ul.hMenu li  {  
  margin: 0;
  padding: 0;
  list-style: none;
  float: left;
  width:140px;
}
ul.hMenu li a { 
  display: block; 
  text-align: left;
  text-decoration: none
}          
ul.hMenu li div  {                    
  position: absolute;               
  display: none;                
}
ul.hMenu div a {
  background: yellow;     
}
ul.hMenu li :hover   {
  background: yellow
}
/**Mouse hover the menus can show up**/
ul.hMenu li:hover div{          
  display:block;
}

Answer №1

I have found a solution that will help you make progress in the right direction.

CSS is not equipped to handle events related to specific keys being pressed. To address this, you will need to utilize javascript or jQuery in this scenario.

The keypress function is what you need to focus on in this case.

While I don't have the exact solution for the tabbing feature, I was able to successfully implement the functionality for pressing the Enter and ESC keys.

Below is the jQuery code snippet:

$('document').ready(function () {
    var menu = $(".hMenu");
    menu.hide();
    $("body").on("keypress", function (e) {
        if (e.keyCode === 13) { //Key Code for Enter
            menu.fadeIn();
        }
        if (e.keyCode === 27) { //Key Code for ESC
            menu.fadeOut();
        }
        if (e.keyCode === 9) { //Key Code for Tab
            //Tabbing function here
        }
    });
});

Check out the sample Fiddle here

This code effectively fades the menu in and out when the corresponding key is pressed.

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

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...

No shadows are visible when using a collada model on a MeshPhongMaterial surface with a spotlight illuminating the scene

I have been trying to solve this issue for a long time but have been unsuccessful. I am attempting to add shadows to my .dea model using MeshPhongMaterial, but the shadows are not appearing. The camera is in the correct position, the ground is made of Mes ...

Is it possible to enhance the appearance of the select2 options in any way?

I am currently using a select2 plugin to handle select boxes, where the options are generated by concatenating two values together. However, I am looking for a way to style one of the values in the select2 box with a different color. Are there any options ...

Creating personalized columns in a BootstrapVue table

I'm having an issue with the b-table component in bootstrap-vue. The array containing my items is structured like this: [{ id: 1, name: "Test", phone: 555-111-666, address: "Some Address", //etc... }] I have a couple of question ...

Toggle the operational status of the bootstrap switch

Does anyone have a solution for customizing the appearance of the Bootstrap switch button when it is disabled? I have successfully styled it for the enabled state, but it defaults to a dark appearance when disabled. I would like the disabled state to have ...

The process of retrieving matching strings from two collections in MongoDB

There are two collections: Collection A consists of: -> {"_id": .... , "data":"demon"} -> {"_id": .... , "data":"god"} and Collection B consists of: -> {"_id": .... , "tit ...

Tips for Transmitting Images with jQuery in ASP.NET

Greetings! I am a newcomer to ASP and I have been contemplating on how to utilize jQuery ajax in order to transmit an image from the input file. My goal is to transfer the path and acquire the image on the server side. Is this achievable? Alternatively, a ...

The MongoDB object type is not stored

Let me share my customized user schema below. var userSchema=mongoose.Schema({ //name:{type:String}, username: {type:String, required:true, unique:true}, password: {type:String, required:true}, habit: {type:Object, required:true} }); Howev ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Transforming unknown JSON data into a fresh JSON structure

An undefined JSON object is being returned to a Node.js/Express.js application from a URL API endpoint http://someserver:someport/some_api_url?_var1=1. This particular JSON input always follows the same format and must be transformed into a new JSON object ...

Using the match.params.id in React: A step-by-step guide

Having some trouble with my React code. I need to display the product name based on its ID, where the product data is fetched from product.js. I am using a router to switch between different products without reloading the page. import product from './ ...

What could be causing the discrepancy in JSON formatting between my data and the examples provided in High

Utilizing jQuery's $.GetJSON method results in the following output: {"Points":[{"X":1,"Y":6},{"X":2,"Y":5},{"X":3,"Y":1},{"X":4,"Y":5},{"X":5,"Y":5},{"X":6,"Y":10},{"X":7,"Y":4},{"X":8,"Y":1},{"X":9,"Y":9},{"X":10,"Y":2}]} Nevertheless, according t ...

In what scenarios would it be appropriate to utilize a checkbox value that is not simply limited to a binary choice of 1 or 0

It has come to my attention that many people on various platforms, including Stack Overflow and my colleagues, use values other than 1 or 0 in their checkboxes (for example, <input type='checkbox' value='check'/>). However, I beli ...

Utilizing React Javascript leaftlet library to implement functionality to zoom in on map using state

As a beginner in programming and leaflet, I've encountered a roadblock in my code. Check out my code snippet: import "./App.css"; import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet"; import { useEffect, useState ...

Enhance Your Website with Jquery and Bootstrap 4: Imrpessive Navbar Effects for Resizing

Hello, I am facing a challenge that my novice mind is struggling to overcome. Utilizing Bootstrap 4 navbar and some jquery, I managed to create a transition where an initially invisible navbar transforms into a solid color when the user scrolls beyond a ce ...

Viewing multiple pages and maintaining sessions in Laravel

I am currently working on a quiz application that involves multiple pages depending on the user's selection. However, I have encountered an issue with Laravel's pagination not saving previous page inputs. Is there a way to resolve this problem? A ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Spacing between a pair of jQuery datepicker panels

https://i.sstatic.net/Xnbh1.png Is there any way to add spacing between two tables inside the jquery date picker with a common header? I've tried various solutions like adding padding to the parent div, but haven't been able to fix it. Can anyon ...

Create a custom JQuery dropdown menu where the title can be changed and other options are easily

I have a question regarding selecting the tiles while also being able to edit the other and input my own text. Apologies for any confusion... A link to the relevant code is provided here Title Mr Mrs Miss Ms Other ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...