Issue
I have created a simple gradient ball.
what I want to do is if I move the mouse cursor anywhere on the page created ball flows along with the mouse cursor. I have added onmousemove event to the JS but it does't really work properly.
please show me the error in my code.
thank you!
let cursor=document.querySelector('.ball');
cursor.addEventListener('onmousemove', (e)=>{
let x= e.pageX;
let y= e.pageY;
cursor.style.left= x+'px';
cursor.style.top= y+'px';
});
.ball{
background-image: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 0%, rgba(4,116,191,1) 60%, rgba(0,212,255,1) 97%);
height: 70px;
width: 70px;
border-radius: 50%;
box-shadow: 0px 0px 13px 1px rgba(9,9,121,0.73);
transition: 0.1s;
pointer-events: none;
position: fixed;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class="ball"></div>
<script src="script.js"></script>
</body>
</html>
Solution
You don't need an eventListener for this. you can just use document.onmousemove.
Then the next issue is that you added the eventlistener to the ball not the window.
Last issue was, that you you sued pageX and pageY while the mouse position is called with clientX and clientY
let cursor=document.querySelector('.ball');
document.onmousemove = function(e) {
let x= e.clientX;
let y= e.clientY;
cursor.style.left= x+'px';
cursor.style.top= y+'px';
};
.ball{
background-image: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 0%, rgba(4,116,191,1) 60%, rgba(0,212,255,1) 97%);
height: 70px;
width: 70px;
border-radius: 50%;
box-shadow: 0px 0px 13px 1px rgba(9,9,121,0.73);
transition: 0.1s;
pointer-events: none;
position: fixed;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class="ball"></div>
<script src="script.js"></script>
</body>
</html>
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.