Is it possible to trigger a keydown event using a forEach loop?

I've been working on implementing an accessibility feature for a bootstrap accordion. I included the tabindex=0 in each <a> tag in an attempt to make it so that when the user presses the tab key, it opens the corresponding dropdown/accordion. However, my current code is opening every accordion option when the tab button is pressed. Is there a way to use a forEach on keydown?

$('.accordion-toggle').keydown(function(e) {
  if (e.keyCode == 13) {
    $('.collapse').addClass('show');
  } else {
    $('.collapse').removeClass('show')
  }
});
<a 
  class="text-left w-100 btn btn-link accordion-toggle" 
  tabindex="0" 
  data-toggle="collapse" 
  data-target="#collapseEight" 
  aria-expanded="true" 
  aria-controls="collapseEight">
    item 1 <i class="arrow down"></i>
</a>

       <div id="collapseSeven" class="collapse" aria-labelledby="headingSeven" data-parent="#accordion">
        <p> Content for this section</p>
        </div>
<a 
  class="text-left w-100 btn btn-link accordion-toggle" 
  tabindex="0" 
  data-toggle="collapse" 
  data-target="#collapseEight" 
  aria-expanded="true" 
  aria-controls="collapseEight">
    item 2 <i class="arrow down"></i>
</a>


       <div id="collapseSeven" class="collapse" aria-labelledby="headingSeven" data-parent="#accordion">
        <p> Content for this section</p>
        </div>

Answer №1

Not exactly what you were looking for, but here is a possible solution. When the tab key is pressed:

  • A slight delay is implemented to allow the document to adjust the tabindex focus
  • If the focused element is an accordion control, all accordions are collapsed first, then the one corresponding to the control's data-target is expanded.

$(document).keydown(function(e) {
  //console.log(e.keyCode)
  if (e.keyCode == 9) {
    setTimeout(() => {
      let $focused = $(':focus');
      if ($focused.hasClass('accordion-toggle')) {
        //close all open ones
        $('.collapsed').removeClass('show');
        $($focused.data('target')).addClass('show')
      }
    }, 50)
  }
});
.collapsed {
  display: none;
}

.collapsed.show {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="text-left w-100 btn btn-link accordion-toggle" tabindex="0" data-toggle="collapse" data-target="#collapseEight" aria-expanded="true" aria-controls="collapseEight">
    item 1 <i class="arrow down"></i>
</a>
<div id='collapseEight' class='collapsed'>Text from collapseEight</div>
<a class="text-left w-100 btn btn-link accordion-toggle" tabindex="0" data-toggle="collapse" data-target="#collapseNine" aria-expanded="true" aria-controls="collapseNine">
    item 2 <i class="arrow down"></i>
</a>


<div id='collapseNine' class='collapsed'>Text from collapseNine</div>

Answer №2

To target a selected accordion and find its parent accordion for collapsing, you can utilize document.activeElement along with a mix of pure JavaScript and jQuery. By running the keydown event at the document level, you can determine if the focused element is an accordion item. Here's a code snippet demonstrating this approach:

$(document).keydown(function(){
    let focused = document.activeElement;
    const pattern = /(?:^|\s)accordion-toggle(?:\s|$)/
    if (document.activeElement.className.match(pattern)) {
        $('.collapse').removeClass('show'); 
        let element = document.activeElement;
        $(element).closest('.accordion-item').find('.collapse').addClass('show');
    }
});

Check out the demo here: https://jsfiddle.net/k86fj5ex/

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

In what ways can you shut down an electron application using JavaScript?

My Electron app is running an express server. Here is the main.js code: const electron = require("electron"), app = electron.app, BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow () { ma ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Creating a dependent picklist feature using node.js and express

I am currently delving into the world of node.js and express. In my node.js application, I am utilizing express along with express-handlebars as the templating framework. My goal is to incorporate a dependent picklist that dynamically renders based on the ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...

Updating parent array values within child components in React

Currently, I am working on a React application where I need to save the handlers for all windows opened from the app. Previously, before using React, I stored these windows in a global array attached to the parent window, although I understand that using J ...

Placing emphasis on an object that appears following a period of waiting

I'm currently working on enhancing the accessibility of a slider that will be featured on my website. The goal is to create an effect where, after clicking (or pressing enter) on the first slide, the focus shifts to the second slide element, allowing ...

employing variable in front of json notation

For my github-gist project, I am using JavaScript and AJAX to customize the file name. Here is the JSON data I am working with: var data = { "description": gist_description, "public": true, "files": { "file.txt" : { "content": gist_conten ...

Retrieving outcomes from a sequence of callback functions in Node.Js

I've been struggling to get my exports function in Node.Js / Express app to return the desired value after going through a series of callback functions. I've spent hours trying to fix it with no success. Can someone provide some guidance? Here is ...

What is the best way to send a Node.js variable to the inner part of a Pug script tag?

I am attempting to pass a variable from my Node.js backend to a Pug template and then use that variable inside a JavaScript script tag within the Pug file. Here's a snippet of my Node.js code: app.get('/profile', function (req, res) { var ...

What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to lear ...

Is Babel necessary for a Node.js server application, and what are the benefits of using it?

My fondness for ES6 syntax and its new object-oriented style makes coding much easier for me. However, as a newcomer to JavaScript, I am curious about the advantages and disadvantages of using Babel in terms of performance, maintenance, readability, and ...

Guide on Showcasing Countries on a Global Map with Various Colors Using react-svg-map

I'm currently working on a project that involves highlighting specific countries on a world map. The default color for the countries is light blue, but I need to change it to dark blue for the highlighted ones. Although the library I'm using has ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

The rotation of Google Maps always returns to its default position when I open the map information window by clicking on it

I have successfully implemented a Google Map with tilt and heading functionality, allowing the map to rotate horizontally. However, I am facing an issue where clicking on a marker resets the map back to its original position. You can view the map by follo ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Transform the post data into a JSON string within the controller

Hello everyone, I have a sample table that I want to share: <table class="table table-bordered" width="100%" cellspacing="0" id="tableID"> <thead> <tr> <th>A</th> <th>B</th> <th>C< ...

Trigger a click event to alter the child div elements

I have a <div> that expands when clicked and shrinks back when clicked again. Inside this div are images that should only appear once the div expands. My issue is ensuring that all images except the first one are hidden until the div expands. https: ...

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...