Вот как я решил эту проблему:
export const addEventListenerArrowUpAndDown = () => {
document.addEventListener("keydown", e => {
// Make sure the drop down is open. In my case, it's shown only
// when the length of my searchResults array is not 0
const searchResultsExist = !!store.getState().search.searchResults.length;
if (searchResultsExist) {
// Pull all elements with a common class name from the drop down (all elements
// usually have only this common class, the rest is too dynamic and unreliable)
const searchResults = Array.from(
document.getElementsByClassName("MuiListItem-root")
);
// I initially tried using .indexOf, but that didn't work, so I'm using this way
let currentlyPseudoHoveredElement = -1;
// See if one of the items already are "hovered" over
searchResults.forEach((element, index) => {
if (element.style.background === "rgba(85, 125, 146, 0.5)") {
currentlyPseudoHoveredElement = index;
}
});
// On Arrow Key down
if (e.keyCode === 40 && !!searchResults.length) {
if (
currentlyPseudoHoveredElement !== -1 &&
currentlyPseudoHoveredElement !== 4
) {
// Set current background color to preferred color
searchResults[currentlyPseudoHoveredElement].style.background =
"#FFFFFF";
// Set next element's background color to preferred color
searchResults[currentlyPseudoHoveredElement + 1].style.background =
"rgba(85, 125, 146, 0.5)";
} else {
searchResults[0].style.background = "rgba(85, 125, 146, 0.5)";
}
}
// On Arrow Key down
else if (e.keyCode === 38) {
if (
currentlyPseudoHoveredElement !== -1 &&
currentlyPseudoHoveredElement !== 0
) {
// Set current background color to white
searchResults[currentlyPseudoHoveredElement].style.background =
"#FFFFFF";
// Set previous element's background color to preferred color
searchResults[currentlyPseudoHoveredElement - 1].style.background =
"rgba(85, 125, 146, 0.5)";
} else {
searchResults[0].style.background = "rgba(85, 125, 146, 0.5)";
}
}
}
});
};
export const addEventListenerOnEnterOpenPseudoHoveredElement = () => {
document.addEventListener("keydown", e => {
if (e.keyCode === 13) {
const searchResults = Array.from(
document.getElementsByClassName("MuiListItem-root")
);
// In the event that the drop down is shown and one of the
// elements is "hovered" over, open that URL that it points to
// This also works if I use the actual mouse to hover over something; it will open the link this way
searchResults.forEach((element, index) => {
if (element.style.background === "rgba(85, 125, 146, 0.5)") {
element.click();
}
});
}
});
};