JavaScript - Mouse Hover Event
A simple code example to implement a mouse hover event using JavaScript.
In the HTML, the <div> tag is specified with the ID 'target' to detect the mouse hover event.
<div id="target"></div>
In CSS, the size and styling are set to define the area for the mouse hover action.
#target {
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
padding: 10px;
color: white;
width: 250px;
height: 250px;
border-radius: 50%;
text-align: center;
cursor: pointer;
user-select: none;
transition: 1s;
cursor: pointer;
background: #ff7f50;
}
The target element is specified using querySelector()
, and the 'mouseover' event is implemented using addEventListener()
when the mouse cursor is over the element.
Additionally, 'mouseleave' is utilized to execute an event when the mouse cursor moves away from the element.
// Implementing mouse hover in event
document.querySelector('#target').addEventListener('mouseover', () => {
// Modifying the HTML inside the target element
document.querySelector('#target').innerHTML = 'Mouse<br>Over';
});
// Implementing mouse hover out event
document.querySelector('#target').addEventListener('mouseleave', () => {
// Modifying the HTML inside the target element
document.querySelector('#target').innerHTML = '';
});