Invert Text Color on Mouse Hover Using CSS and JavaScript
To achieve the desired hover effect, where black text inverts to white while maintaining the appearance of a black cursor, we can combine the capabilities of CSS clip-paths with JavaScript event handling.
The approach consists of creating two layers of text: the primary text layer and an inverted text layer. The inverted text layer is positioned behind the primary text layer and has its text color set to white.
Using JavaScript, we capture the mouse movement and dynamically adjust the clip-path of the inverted text layer. As the mouse moves, the clip-path is adjusted to reveal more of the inverted text, creating the illusion of the primary text inverting its color.
Here's a breakdown of the key code components:
/* Primary Text Layer */
h1 {
color: #000;
position: relative;
}
/* Inverted Text Layer */
h1:before {
position: absolute;
content: attr(data-text); /* Same text as primary layer */
color: #fff;
background: #000;
clip-path: circle(0 at var(--x, -100%) var(--y, -100%)); /* Dynamic Clip-path */
}
/* Cursor */
.cursor {
position: fixed;
width: 40px;
height: 40px;
background: #000;
border-radius: 50%;
transform: translate(-50%, -50%);
z-index: -2;
}
// Event Listener for Mouse Movement
document.body.onmousemove = function(e) {
// Update cursor position
cursor.style.left = e.clientX 'px';
cursor.style.top = e.clientY 'px';
// Update clip-path of inverted layer based on mouse position
h1.style.setProperty('--x', (e.clientX - p.top) 'px');
h1.style.setProperty('--y', (e.clientY - p.left) 'px');
};
Example Code:
WORK
Result:
When you hover over the "WORK" text, the black text will gradually transition to white as the mouse cursor moves.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3