Element search feature added to dropdown menu

I am seeking valuable advice and guidance to navigate through this challenging situation.

Here's the scenario: I need to create a dropdown menu similar to the one below.

<ul class="dropdown">
<li><a href="#">America</a></li>
<li><a href="#">Brazil</a></li>
<li><a href="#">China</a></li>
<li><a href="#">Denmark</a></li>
<li><a href="#">Egypt</a></li>
</ul>

The goal is to enable keyboard navigation through the items in the dropdown. For example, pressing "E" should focus on Egypt.

While UL>Li doesn't allow for this functionality, we can use the Select tag instead.

<select class="dropdown">
<option>America</option>
<option>Brazil</option>
<option>China</option>
<option>Denmark</option>
<option>Egypt</option>
<select>

However, styling the dropdown becomes an issue with the Select tag as CSS padding may not work across all browsers.

My question is how can I create a dropdown with these 3 functionalities:

1. Open on Tab key press 
2. Navigate listed items using keyboard input.
3. Style the dropdown for cross-browser compatibility.

I have searched extensively online but haven't found a perfect solution, except for this plugin:

Unfortunately, I am unable to use external plugins at work. The only tools I have at my disposal are Bootstrap, jQuery, JavaScript, CSS, and HTML (no Angular).

If anyone can assist me with this, I would greatly appreciate it.

Answer №1

Styling a <select> dropdown consistently across all browsers is a challenge that has no universal solution. Some plugins like Bootstrap Select and Chosen use JavaScript and custom markup to create a fake <select>, but this can negatively impact accessibility.

In my opinion, sticking with the default browser styling for the <select> element is the best approach.

While you may not be able to style the dropdown itself without compromising accessibility, you can customize the toggle button. Here are some resources for achieving this:

Alternatively, consider coding the countries as a list of links that expands with JavaScript. Just make sure to include the appropriate aria roles for accessibility.

Answer №2

1. Implementing Toggle Functionality on Tab Key Press

Implementing a toggle functionality for the dropdown on the Tab key press of the ul element may not be the best approach, as the Tab key serves various other functions within the window. This can lead to buggy behavior, especially when focus needs to be shifted elsewhere. However, if you are working with an input element like select, then this method is acceptable.

To demonstrate this concept without relying on external libraries, I have created a simple mock-up using solely JavaScript. The example utilizes a ul element for the dropdown. Feel free to check out the implementation in this JS Fiddle: JS Fiddle

HTML :

<div>
  <ul id="dropdown">
    <li class='highlight' data-key='A'><a href="#">America</a></li>
    <li data-key='B'><a href="#">Brazil</a></li>
    <li data-key='C'><a href="#">China</a></li>
    <li data-key='D'><a href="#">Denmark</a></li>
    <li data-key='E'><a href="#">Egypt</a></li>
  </ul>
</div>

CSS :

ul {
  list-style: none;
  display: none;
}

ul li.highlight {
  background: yellow;
}

Javascript :

document.addEventListener("keydown", keyDownListener, false);

function keyDownListener(e) {
  var keyCode = e.keyCode;
  var dropdwn = document.getElementById('dropdown');
  if (keyCode == 9) {
    dropdwn.style.display = (dropdwn.style.display != 'none' ? 'none' : 'block');
  } else if (dropdwn.style.display != 'none') {
    var items = dropdwn.getElementsByTagName("li");
    items[0].classList.remove("highlight");
    for (var i = 0; i < items.length; ++i) {
      var aKey = items[i].dataset.key;
      if (String.fromCharCode(e.keyCode) === aKey) {
        for (var j = 0; j < items.length; ++j) {
          items[j].classList.remove("highlight");
        }
        items[i].classList.add("highlight");
      }
    }
  }
}

Explanation :

  1. Add a keydown event listener to the document.
  2. Toggle the visibility of the dropdown on pressing the Tab key.
  3. If any other key is pressed while the dropdown is visible, compare the pressed key with the data-key of each li. Highlight the corresponding item if there is a match.

It's important to note that toggling the ul dropdown on Tab key press can impact accessibility. For a select dropdown, this behavior is more suitable.

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

streaming audio data from a MongoDB database to an HTML audio element

As part of my current project, I am delving into the realm of creating an audio player. The concept of database storage for files is relatively new to me, as my previous experience has mainly involved storing strings. Up to this point, here's what I ...

Changing the row property value of a textarea dynamically based on text input in ReactJS

Here is what I have tried: <textarea rows='2' onChange={e => setSomething(e.target.value)} className='form-control text-area ' value={something} placeholder='write something'> </textarea> output: https://i ...

The ajax request does not support this method (the keydown event is only active during debugging)

I've encountered a strange issue with an AJAX request. The server-side code in app.py: #### app.py from flask import Flask, request, render_template app = Flask(__name__) app.debug = True @app.route("/myajax", methods=['GET', ...

Display the chosen option in the console by using onChange() function; this is analogous to how onSelect()

I'm having trouble getting the value of a select element to log in the console. I managed to do this with an onSelect() method, but the onChange() method isn't returning anything. Here's what I tried with the onChange() method: <Form.Gr ...

javascript Initiate JSON parsing with preset value

In order to parse JSON into a JavaScript object with data, I am providing a simple example below: var IsTrue = true; var Number = 9; var Object = { a : 1}; var Array = [10,6]; var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Ar ...

Encountering an abundance of concurrent requests using NodeJS and request-promise

I am currently working on a NodeJS project that involves a large array of about 9000 elements containing URLs. These URLs need to be requested using the "request-promise" package. However, making 9000 concurrent GET requests to the same website from the sa ...

Angular: Trigger service worker to handle push notification event from service

Is it possible to call the service worker push event from a custom service in Angular? I implemented this code in my service, and it works on desktop and android, but not on iPhone. navigator.serviceWorker.register('sw.js'); Notification.request ...

Is the XMLHttpRequest.onreadystatechange event still triggered behind the scenes when Promises are utilized?

Imagine I am utilizing a Promisified API for executing an Ajax Request, would the event-loop still resort to calling the basic XMLHttpRequest.onreadystatechange? Although using Promisfying enables coding in a sequential manner, essentially it is still rel ...

Selection List dictates the necessity of JavaScript

I need to create a JavaScript code that will require the comment field (textarea) when a selection is made from a list. Currently, I have added a required icon next to the comment section but I am stuck at this point. See the code below. Thank you in adva ...

Filtering Images by Alt Attribute: A Comprehensive Guide

I'm working on an image gallery project that includes a search box feature. My goal is to dynamically hide images that do not have an alt attribute matching the user's search query. Despite several attempts, I keep encountering issues where all e ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

Issue with vue-router not displaying template for nested routes

My route configuration looks like this: const routes = [{ path: '/', component: Home, children: [ { path: "/health", children: [ { path: 'overview', ...

Creating a way for a Node and React application to share classes

I am in the process of developing a Node and React application, both implemented using TypeScript. The directory structure of my project is illustrated below: https://i.sstatic.net/914A1.png My query: Given that I am utilizing the same programming langu ...

Error encountered while trying to authenticate user through post request

I have written a post route request function below to handle user login. However, I keep encountering 401 unauthorized errors when making the request. Can anyone suggest any modifications or refactorings that could potentially fix this issue? Thank you i ...

In Vue 3, what causes the dynamic class value to change along with the ref value when using a function with the ref property for binding?

I'm currently working on Vue code that looks like this. <template> <h1 :class="{ disabled: checkClass() }">Hello</h1> </template> <script setup lang="ts"> import { ref } from "vue"; const ...

Steps for exporting a module from a JavaScript file that is linked:

When I include the main.js file in my project, the code below works properly: modules.exports = { property: value } However, if I include it in a web page like this: <!DOCTYPE html> <html> <head> <script src="main.js"& ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Dimensions by the height of the content

In this particular div block, I have set a height as shown below: <div> <!-- content --> </div> Along with the following styles: div{ height:100px; } However, I am interested in dynamically adjusting the height of the div base ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...