I am looking to enhance my user experience by allowing them to either hover over an option to highlight it or press a number key to highlight the corresponding option. However, I am facing an issue where the object.style.backgroundColor function overrides the hover effect defined in my CSS file. This means that pressing any key eliminates the hover effect. Is there a solution to this problem?
<!-- My HTML -->
<head>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<p id='option1'>option 1</p>
<p id='option2'>option 2</p>
<p id='option3'>option 3</p>
<script src="test.js"></script>
</body>
/* My CSS */
p {
background-color: red;
}
p:hover {
background-color: blue;
}
/* My JavaScript */
// Highlights option based on keyup
document.addEventListener("keyup", function(event) {
unhighlightOption(); // To unhighlight any already highlighted elements
switch (event.which) {
case 49: // 1
case 97: // Numpad 1
document.getElementById('option1').style.backgroundColor = 'blue';
break;
case 50: // 2
case 98: // Numpad 2
document.getElementById('option2').style.backgroundColor = 'blue';
break;
case 51: // 3
case 99: // Numpad 3
document.getElementById('option3').style.backgroundColor = 'blue';
break;
default:
console.log('Not a valid key');
}
});
// Loop to unhighlight all options
function unhighlightOption() {
for (let i=1; i<4; i++) {
document.getElementById('option' + i).style.backgroundColor = 'red';
}
}
I have attempted using addEventListener("mouseenter", function() {code}) for highlighting and addEventListener("mouseleave", function() {code}) for unhighlighting. However, I would prefer to maintain most of my styles in the CSS file if possible.