Categories
Web development

CSS/JS Eye Follows Mouse Cursor + Blink on Hover

CSS/JS Eye Animation

Demo:

*to see the CSS/JavaScript Eye Animation on the website click here.

To create the CSS/JavaScript Eye Animation follow the steps below and watch the video tutorial:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript

Step1.

Add HTML

Create the container with the eyeball, iris, and eyelid:

<div class="container">
  <div class="eyeBall">
    <div class="iris"></div>
  </div>
  <div class="eyeLid"></div>
  <div class="lid"></div>
</div>

Step2.

Add CSS

Set the colour and the position of the background and elements:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  position: relative;
  cursor: pointer;
}

Style the eye:

.iris {
  position: absolute;
  width: 70px;
  height: 70px;
  border: 5px solid #333;
  background-color: #0077b6;
  border-radius:50%;
  left:40px;  
  top:30px;
}

.iris:before {
  content:"";
  position: absolute;
  background-color: #333;
  border-radius:50%;
  width:40px;
  height: 40px;
  top:22%;
  left:22%;
}

.iris:after {
  content:"";
  position: absolute;
  background-color: rgba(255,255,255,0.4);
  border-radius: 50%;
  width:15px;
  height:15px;
  top:35%;
  left:65%;
  box-shadow: -35px 20px rgba(255,255,255,0.4);
}

.eyeBall {
  position: relative;
  width: 150px;
  height: 150px;
  background-color: transparent;
  border: 5px solid #333;
  border-radius:100% 0;
  box-shadow: inset 5px 5px 5px rgba(0,0,0,0.3);
  transform: rotate(45deg);
  top:-10px;
  z-index:1;
  overflow: hidden;
}

.eyeLid {
  position: absolute;
  border-top: 5px solid #333;
  border-left: 5px solid #333;
  border-radius:100% 0;
  width: 150px;
  height: 150px;
  top:-30px;
  left:3px;
  transform: rotate(45deg);
  transition: .2s;
  z-index:10;
}

.lid {
  position: absolute;
  z-index:9;
  background-color: #fff;
  width: 295px;
  height: 270px;
  border-radius:50%;
  top:-248px;
  left:-68px;
  transition: .2s;
}

To make the eye blink add transition on hover:

.container:hover .eyeLid {
  transform: rotate(-45deg) rotateX(160deg);
}

.container:hover .lid {
  transform: translateY(90px);
}

Step3.

Add JavaScript

const eye = document.querySelector('.iris');
window.addEventListener('mousemove', (event) => {
const x = -(window.innerWidth / 2 - event.pageX) / 35;
const y = -(window.innerHeight / 2 - event.pageY) / 35;
eye.style.transform = `rotate(-45deg) translateY(${y}px)  translateX(${x}px)`;         
        }); 

Watch also the video tutorial:

Enjoy coding!

Read also:

CSS & jQuery Eye Animation

CSS & JavaScript Image Magnifier Glass

CSS & JavaScript Bee Progress Bar