visit
<div class="eye eye-left">
<div class="eye-inner"></div>
</div>
<div class="eye eye-right">
<div class="eye-inner"></div>
</div>
.eye {
display: flex;
width: 48px;
height: 48px;
position: absolute;
bottom: 41px;
background: #fff;
border-radius: 50%;
&-left {
left: 26px;
}
&-right {
right: 26px;
}
}
.eye {
&-inner {
position: relative;
display: inline-block;
border-radius: 50%;
width: 40px;
height: 40px;
background-color: black;
border-radius: 50%;
margin-left: 4px;
margin-top: 4px;
}
}
.eye {
&-inner {
&:after {
position: absolute;
top: 2px;
left: 10px;
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
content: ' ';
}
}
}
const container = document.querySelector('.container');
container.addEventListener('mousemove', e => {
// Ok mouse is moving!
});
const eyes = document.querySelectorAll('.eye');
[].forEach.call(eyes, function(eye) {});
const container = document.querySelector('.container');
container.addEventListener('mousemove', e => {
const eyes = document.querySelectorAll('.eye');
[].forEach.call(eyes, function(eye) {
// Get the mouse position on the horizontal axis
let mouseX = eye.getBoundingClientRect().right;
// If it's the left eye we need the left offset instead the right
if (eye.classList.contains('eye-left')) {
mouseX = eye.getBoundingClientRect().left;
}
// Now we also need the vertical offset
let mouseY = eye.getBoundingClientRect().top;
// Now we are going to calculate the radian value of the offset between the mouse and the eye
let radianDegrees = Math.atan2(e.pageX - mouseX, e.pageY - mouseY);
// Let's convert this into a degree based value so we can use it in CSS
let rotationDegrees = radianDegrees * (180 / Math.PI) * -1 + 180;
// Now all we have to do is add this degrees to our eye!
eye.style.transform = `rotate(${rotationDegrees}deg)`;
});
});
Previously published at