Reputation: 23
I want a function that overwrites the e.clientY and e.clientX when i hover on the navbar so that the cursor would be in the middle of the background circle. Can anybody please help?
const cursor = document.querySelector('#cursor');
document.addEventListener("mousemove", function(e) {
cursor.setAttribute("style", "top: " + (e.clientY - 10) + "px; left: " + (e.clientX - 10) + "px;")
})
document.getElementById("navbarimg").addEventListener("mouseover",function(e) {
cursor.classList.toggle("hover")
})
document.getElementById("navbarimg").addEventListener("mouseout",function(e) {
cursor.classList.toggle("hover")
})
body{margin:0;height:100vh;background:rgb(27,27,27);}
#cursor{width:30px;height:30px;border:2px solid gray;border-radius:50%;position:fixed;transition-duration: 100ms;transition-timing-function: ease-out;}
#navbarimg{position:absolute;top:50%;left:50%;transform:tranlate(-50%,-50%);}
#cursor.hover{width:100px;height:100px;opacity:0.1;background-color:gray;}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cursor</title>
</head>
<body>
<div id="cursor"></div>
<div class="nav">
<a href="../"><img id="navbarimg" src="navbar.svg" alt="navbar"></a> </div>
</body>
Upvotes: 2
Views: 47
Reputation: 272994
Simply add transform: translate(-50%, -50%);
to the cursor and no need any offset
const cursor = document.querySelector('#cursor');
document.addEventListener("mousemove", function(e) {
cursor.setAttribute("style", "top: " + (e.clientY) + "px; left: " + (e.clientX ) + "px;")
})
document.getElementById("navbarimg").addEventListener("mouseover", function(e) {
cursor.classList.toggle("hover")
})
document.getElementById("navbarimg").addEventListener("mouseout", function(e) {
cursor.classList.toggle("hover")
})
body {
margin: 0;
height: 100vh;
background: rgb(27, 27, 27);
}
#cursor {
width: 30px;
height: 30px;
border: 2px solid gray;
border-radius: 50%;
position: fixed;
transform: translate(-50%, -50%);
transition-duration: 100ms;
transition-timing-function: ease-out;
}
#navbarimg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#cursor.hover {
width: 100px;
height: 100px;
opacity: 0.1;
background-color: gray;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cursor</title>
</head>
<body>
<div id="cursor"></div>
<div class="nav">
<a href="../"><img id="navbarimg" src="navbar.svg" alt="navbar"></a>
</div>
</body>
Upvotes: 1