Link Background Highlight
Visual feedback for menus. Learn how to toggle background styles using JavaScript event listeners for `onmouseover` and `onmouseout`.
Copy the Script
<script>
function bgOn(elem) {
elem.style.backgroundColor = "#ffeb3b"; // Yellow
elem.style.color = "#000";
}
function bgOff(elem) {
elem.style.backgroundColor = ""; // Default
elem.style.color = "";
}
</script>
<a href="#" style="display:block; padding:10px;"
onmouseover="bgOn(this)"
onmouseout="bgOff(this)">
Hover Me
</a>
Frequently Asked Questions
Not strictly. CSS `:hover` is the standard modern way (`background-color: red;`). However, JavaScript allows for more complex logic, like playing a sound or logging analytics on hover.
Yes, but it looks best on `display: block` or `inline-block` links (like buttons or sidebar items) so the background fills a rectangular area.
Yes. Add `transition: background-color 0.3s;` to the CSS class of the element for a smooth fade effect.