I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position.
The size of the cursor should match the width and height of the text being hovered over, and its position should correspond to the offset Y and X of that text while hovering.
Currently, my code is not working as expected. Any suggestions on how to improve it? Thank you for your help!
let cursor = document.querySelector('.cursorFollower');
let button = document.querySelector('.superText');
let buttonWidth = button.offsetWidth;
let buttonHeight = button.offsetHeight;
let buttonX = button.offsetLeft;
let buttonY = button.offsetTop;
document.addEventListener('mousemove',(e)=>{
cursor.style.left = e.pageX - 10 + 'px';
cursor.style.top = e.pageY - 10 + 'px';
});
button.onmouseover = function(){
button.setAttribute("style", "color: #84C4B5;");
cursor.style.transform = 'rotate(0deg)';
cursor.style.width = buttonWidth + 'px';
cursor.style.height = buttonHeight + 'px';
cursor.style.top = buttonY + 'px';
};
button.onmouseout = function(){
button.setAttribute("style", "color: white;");
cursor.style.transform = 'rotate(45deg)';
cursor.style.width = '20px';
cursor.style.height = '20px';
};
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width:100%;
height: 100vh;
background-color: #0A193E;
color: white;
font-family: sans-serif;
font-size: 20px;
}
.superText {
padding: 10px 20px;
cursor: none;
transition: all 0.2s ease;
}
.cursorFollower {
width: 20px;
height: 20px;
position: absolute;
border: 1px solid white;
transition: all 0.2s ease-out;
pointer-events: none;
transform: rotate(45deg);
}
<div class="container">
<p class="superText">Hello World!</p>
</div>
<div class="cursorFollower"></div>