I'm working on a site with one central element and I would like for this element to interact with the cursor. This is what I have so far:
var hello = document.getElementsByClassName("hello");
document.onmousemove = function() {
var x = event.clientX * 100 / window.innerWidth + "%";
var y = event.clientY * 100 / window.innerHeight + "%";
for(var i=0;i<hello.length;i++) {
hello[i].style.left = x;
hello[i].style.top = y;
hello[i].style.transform = "translate(-" + x + ",-" + y + ")";
}
}
* {
padding: 0;
margin: 0;
}
body {
background-color: black;
}
.hello_wrapper_wrapper {
position: absolute;
background-color: none;
/* background-color: blue */
width: 35vw;
/* This object has to be larger than: width: 300px; height: 150px; */
height: 35vh;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.hello_wrapper {
position: relative;
background-color: none;
width: 35vw;
height: 35vh;
}
.hello {
position: absolute;
background-color: white;
width: 300px;
height: 150px;
text-align: center;
line-height: 150px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<!doctype html>
<html lang="EN">
<head>
<meta charset="UTF-8">
<title> 0 </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="hello_wrapper_wrapper">
<div class="hello_wrapper">
<div class="hello">
Hello World!
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Note: The main element is inside of a: wrapper (width: 35vw; height: 35vh;), the main element, called: hello has the following dimensions: hello (width: 300px; height: 150px;). – hello has to be bigger than the wrapper for this to work, so I would change the size of the preview-window, when looking at the fiddle.
I would like to add some sort of easing to the element, I don't want it to jump around or move too quickly, I would like for it to be a bit sluggish, follow the curser, but drag a little bit behind. Also, when the curser is not hovering over the page, the page is reloaded and the curser then enters the page, the box jumps and, again, I'd just like to make this more smooth.
I would very much appreciate it, if someone could help me with this. Thank you!
Credits: https://www.youtube.com/watch?v=AixAmLWzXYg (This is a tutorial I followed.)