Skip to content

Commit 927c946

Browse files
committed
Make dropdown work with keyboard navigation and add aria attributes
1 parent 639b5af commit 927c946

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/javascript/vanilla-js-dropdown.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@ var CustomSelect = function(options) {
4040

4141
button.className = titleClass;
4242
button.textContent = selectOptions[0].textContent;
43+
button.setAttribute('aria-expanded', false);
4344

4445
// creating the UL
4546
var ul = document.createElement('ul');
4647
ul.className = listClass;
48+
ul.setAttribute('aria-hidden', true);
4749

4850
// dealing with optgroups
4951
if (selectOpgroups.length) {
@@ -64,6 +66,11 @@ var CustomSelect = function(options) {
6466
selectContainer.appendChild(ul);
6567

6668
selectContainer.addEventListener('click', onClick);
69+
selectContainer.addEventListener('keypress', function(event) {
70+
if (event.key === 'Enter') {
71+
onClick(event);
72+
}
73+
});
6774

6875
// pseudo-select is ready - append it and hide the original
6976
elem.parentNode.insertBefore(selectContainer, elem);
@@ -81,6 +88,7 @@ var CustomSelect = function(options) {
8188
li.innerText = options[i].textContent;
8289
li.setAttribute('data-value', options[i].value);
8390
li.setAttribute('data-index', index++);
91+
li.setAttribute('tabindex', '0');
8492

8593
if (selectOptions[elem.selectedIndex].textContent === options[i].textContent) {
8694
li.classList.add(selectedClass);
@@ -141,6 +149,8 @@ var CustomSelect = function(options) {
141149
*/
142150
function toggle() {
143151
ul.classList.toggle(openClass);
152+
ul.toggleAttribute('aria-hidden');
153+
button.toggleAttribute('aria-expanded');
144154
}
145155

146156
/**
@@ -150,6 +160,8 @@ var CustomSelect = function(options) {
150160
*/
151161
function open() {
152162
ul.classList.add(openClass);
163+
ul.setAttribute('aria-hidden', false);
164+
button.setAttribute('aria-expanded', true);
153165
}
154166

155167
/**
@@ -159,6 +171,8 @@ var CustomSelect = function(options) {
159171
*/
160172
function close() {
161173
ul.classList.remove(openClass);
174+
ul.setAttribute('aria-hidden', true);
175+
button.setAttribute('aria-expanded', false);
162176
}
163177

164178
return {

0 commit comments

Comments
 (0)