In CSS, we can very easily apply the hover effect on elements using external CSS. But you might sometimes need to apply the hover effect using inline CSS only, e.g. styling the email templates.
If you try to add the :hover
pseudo-class selector in the inline CSS, it is not going to work at all. This is because CSS does not allow adding selectors in the inline CSS.
But we can still apply exactly the same hover effect to an element without using any external CSS.
To do that we can use JavaScript’s onMouseOver
and onMouseOut
events.
The onMouseOver
event is fired as soon as we move the mouse pointer onto the element. Similarly, the onMouseOut
event is fired as soon as we take the mouse pointer away from the element.
So, for e.g. if you want to change the background color of a div element from orange to red on mouse hover, you have to set the red background on the onMouseOver
event.
Now, you have to change it back to its original background color i.e. red using the onMouseOut
event. If you don’t do this, the background color of the element will remain red even if you take the mouse pointer away from the element.
Here is a working example which changes the background color of the div to red on mouse hover:
Example:
<div onMouseOver="this.style.backgroundColor='red'" onMouseOut="this.style.backgroundColor='orange'"> Hover Over Me! </div>
You can use exactly the same process to change the color of a link(<a>
tag) on mouse hover.
Here is an example:
Example:
<a href="#" onMouseOver="this.style.color='red'" onMouseOut="this.style.color='blue'"> Hover Over This Link! </a>