In this tutorial we will learn How to Change Text Color On Hover using JavaScript. onmouseover event can be used to create hover effect and JavaScript style property can be used to change text color of element.
Table of Contents
onmouseover event
onmouseover event occurs when mouse cursor is moved over a HTML element.
In this example onmouseover event will execute a JavaScript function to change the text color of div tag which will mimic the on hover effect.
style property
style property returns the style properties and values of HTML element.
In this example style property is used to change text color of div.
HTML Code
HTML Code is given below, in this code we have a div tag with onmouseover event and onmouseout event.
onmouseout event is used to revert the changes made.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Change Text Color On Hover</title>
</head>
<body>
<div onmouseover="mouseOver(this)" onmouseout="mouseOut(this)">
Hover Over me to change my Color!
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function mouseOver() will change text color of div on mouse hover.
element represent the tag which has triggered the onmouseover event.
The mouseOut() will be executed when mouse cursor is moved out of element.
<script>
function mouseOver(element)
{
element.style.color = 'red';
}
function mouseOut(element)
{
element.style.color = 'black';
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Change Text Color On Hover using JavaScript.