Steer your keyboard attention towards the parent element that embodies a list

My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events.

The goal of keyboard accessibility includes:

  1. Tab key to navigate the menu elements.
  2. Pressing the down arrow key opens a focused menu.
  3. Using the tab key in the menu helps navigate through its elements.
  4. Pressing the esc key closes the drop-down menu.
  5. Upon closing, maintain focus on the parent element of the menu.

Check out the jsFiddle example for a full implementation.

Issue: How can I return to the initial parent element after closing the drop-down menu with the esc key? This prevents users from having to tab back to their original location.

I appreciate any help!

HTML

<ul class="menu">
    <li>
        <a href="#">Menu Elem</a>
        <div class="subMenu">
            <ul>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
            </ul>
        </div>
    </li>
    <li>
        <a href="#">Menu Elem</a>
        <div class="subMenu">
            <ul>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
            </ul>
        </div>
    </li>
    <li>
        <a href="#">Menu Elem</a>
        <div class="subMenu">
            <ul>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
                <li>
                    <a href="#">Sub Menu Elem</a>
                </li>
            </ul>
        </div>
    </li>
</ul>

CSS

.menu > li {
    display: inline-block;
    text-align: center;
    color: white;
    background-color: orange;
    width: 100px;
    height: 70px;
        position: fixed;
}

.menu > li:hover {
    cursor: pointer;
}
.menu > :nth-child(1) {
    left: 1px;
}
.menu > :nth-child(2){
    left: 102px;
}

.menu > :nth-child(3){
    left: 203px;
}
.menu > li > a {
    line-height: 70px;
}
.menu > li > .subMenu {
    display: none;
    width: 200px;
    margin-top: 1px;
    outline: 1px solid black;
}
.menu > li > .subMenu > ul > li {
    height: 100px;
    background-color: green;
    margin-left: -40px;
    line-height: 100px;
}
.menu > li > .subMenu > ul > li:hover {
    background-color: purple;
    cursor: pointer;
}
a {
    text-decoration: none;
    color: white;
}

JS/jQuery

$(document).ready(function(){
    var menuElem = $(".menu > li");

    $(menuElem).hover(function(){
        $(this).find(".subMenu").toggle();
    });

    $(menuElem).keydown(function(e) {
        // down arrow key
        if(e.keyCode === 40 && $(this).find(".subMenu").is(":hidden")){
            $(this).find(".subMenu").toggle();
        }
        // esc key
        else if(e.keyCode === 27 && $(this).find(".subMenu").is(":visible")){
            $(this).find(".subMenu").toggle();

            // ***** problematic code here *****
            // Need to target the <a> element, or the <li> element, or the <div>, or the <ul> element, not sure which one will work.
            // Currently: trying to get whichever element represents the selected menu, in the below case the anchor element

            $(menuElem).eq($(this).index()).find("a").addClass("selected");
        }
    });
});

Answer №1

To target the parent's a element and give it focus, you can utilize the method .focus()

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 issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...

Why does the diamond symbol appear distorted on my iPhone screen?

My website is similar to SO where moderators have a diamond sign at the end of their name. However, I am facing an issue on my iPhone where the diamond sign looks red and distorted (on Chrome it appears normal). https://i.sstatic.net/RnpyP.jpg As you can ...

Utilize a Java application to log in to a website automatically without the need to click on

Opening two websites in my application is a requirement. Both of these websites have login forms with the action set to POST method. My goal is to automatically redirect to the next page after logging into these websites when I access them through my proj ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

Puppeteer causes Express to stop listening to incoming requests

As I work on developing a straightforward API that utilizes Puppeteer to execute actions, I encounter an issue where my Express app stops listening once Puppeteer is launched. Below is the script in question: const Apify = require('apify'); cons ...

Maintain form activity post submission using jQuery's addClass and removeClass methods

There is a button on my website that, when clicked, reveals a form. The code I am using for this functionality is: $('#theform').addClass('hidden') $('#theform').removeClass('hidden'); <div id="theform" c ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

What's the reason for jQuery not triggering my Ajax error handler?

Here's the jQuery Ajax call I am working with (There are no other global settings/handlers): $.ajax( { url: "http://www.blah.com/url/does/not/exist", type: "get", data: someData, dataType: "json", error: function (xhr, msg, ex) { ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Mixing up letters using a shuffle function

Seeking assistance as a newcomer here. I have a shuffle function triggered by pressing the reset button with class="reset" on the img tag. How can I make it load shuffled from the start? So that when loading this page, the letters do not appear in alphabet ...

Dynamic Automatic URL Refresh with Javascript

Hey there! Just joined this community and I'm still a coding newbie. I'm trying to figure out how to make an external JavaScript URL automatically refresh every 30 seconds. The URL looks something like this: domain.com/filename.js The tricky pa ...

From HTML to Python CGI to communication with a Serial port

I am having an issue running a Python CGI script to send data to a serial port. Whenever I try to open and set the serial port to a variable, the HTML server crashes. Below is the code snippet that receives a color (red, blue, green) from the HTML page: ...

issue with manipulating hidden field on the client side

After some troubleshooting, I discovered an issue with a hidden field in my form. Despite changing the value using JavaScript right before submitting the form, on the server side it appeared to be null or empty. The Request.Form["hidAction"] showed as em ...

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

Replace the single text area with multiple div elements and update the image within each div

Within the 'Pinctitle' area, there is text that I want to change each time a Pselectorbutton is hovered over with a fading effect. Additionally, I would like the image inside the 'Pselectorbutton' to change at the same time. Currently, ...

List arranged in order with a hyperlink in the center and an image positioned on the right side

I am trying to create an ordered list with a link to an article in the middle and a small png image file positioned directly to the right of it. For reference, here is an image depicting the exact type of list that I am aiming to achieve: https://i.stack. ...

Is there a way to determine in jQuery's $.ajax callback 'complete' whether a request was successful?

Within my ajax complete callback, I have large code blocks where I need to verify the success of an ajax request: $.ajax(function() { url: 'http://hostname.com', data: myData, dataType: 'json', complete: function(data) ...

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

Problem integrating multer with Express JS and Node JS

Click here to access the server.js file on GitHub Following a tutorial, I have implemented code accordingly. However, when working with an updated version of Express JS, errors are being thrown on the side of Express JS. Error C:\nodefiles&bso ...

When the Add button in AngularJS is clicked, a new popup page should appear by concealing the parent page

I am currently working on a project that involves using the AngularJS/Breeze framework within the HotTowel Template. One of the requirements I have is to include a button/link labeled "Add" on the parent.html page. When this button is clicked, it should t ...