Creating a Mouse Tracking Eye Effect With JavaScript

Creating a Mouse Tracking Eye Effect With JavaScript

Introduction

Animations play a major role in an interactive user experience. One such example of this is the mouse-tracking eye effect in JavaScript.

The basic idea is that the eyes of an illustration, character or cartoon figure follow your mouse wherever it moves on a web page. It is a cool way of keeping the user invested and interested in your page.

This effect is commonly seen on contact forms where, when you either type something or move the cursor, the eyes follow you. A couple of examples of this:

In our case, we will simply create the eyes as opposed to a complete character. Our final effect will look something like the header image above once we are done. So let’s get started!


Creating the Eyes with HTML and CSS

First, let's create a static pair of eyes using HTML elements and CSS stylings.

The HTML Structure

The HTML markup is pretty simple. We will create a container or div called eyes. Inside this, we will have each eye element. Both will also have a div called pupil which will be the black circle within the white eye.

<div class="eyes">
  <div class="eye">
    <div class="pupil"></div>
  </div>
  <div class="eye">
    <div class="pupil"></div>
  </div>
</div>

The CSS Styling

We will first set the background of the body to black. The eyes div will have a width of 100% and we will give it a display of flex. The display flex allows us to centre the eyes and also give a gap between them. Next up, we will style the white part of the eye. We will give it a slightly oval shape. It will also have a display of flex to centre the black pupil within.

body {
  background-color: #000;
}

.eyes {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  column-gap: 20px;
}

.eye {
  width: 85px;
  height: 70px;
  border-radius: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pupil {
  width: 40px;
  height: 40px;
  border-radius: 101px;
  background-color: #000;
}

Our static pair of eyes will now look like this:

Static JavaScript pair of eyes

Creating The Mouse Effect

Now let's see how to animate our static eyeballs using JavaScript so that they follow the mouse around.

Getting the X and Y position of the mouse with JavaScript

To move the eyes as we move the mouse, we need to first get the x and y positions of the mouse. The basic logic here is that we will add a mousemove event listener to the window. Then, we will use the event.pageX or event.pageY property to get the X or Y coordinate at which the mouse was clicked.

Getting The Exact Relative Position

But to get the exact relative position of the mouse to an eye (or element), we need to subtract the position of the parent element from the mouse position calculated earlier. A simple way to do this is to use the getBoundingClientRect() method, which returns data about the size of an element and its position relative to the viewport.

For the X Position, we will subtract the left offset of the element from the X coordinate of the mouse.

For the Y position, we will subtract the top offset from the Y coordinate.

// get both pupils
const pupils = document.querySelectorAll(".eye .pupil");
window.addEventListener("mousemove", (e) => {
  pupils.forEach((pupil) => {
    // get x and y position of cursor
    var rect = pupil.getBoundingClientRect();
    var x = (e.pageX - rect.left)
    var y = (e.pageY - rect.top)
  });
});

Also, we are looping through each pupil and getting its X and Y position.

Moving the Pupils with JavaScript

To move the pupils, we will use the transform3d css property. We need to give it 3 parameters, the X, Y and Z values. However, right now our values are very large. To convert them, we will divide the X and Y coordinates or positions by 30. This divisor can be any number and can be perfected using trial and error. But it should be around the same magnitude as the width of each pupil.

The Z value will be set to 0. The final JavaScript code will look like this:

// get both pupils
const pupils = document.querySelectorAll(".eye .pupil");
window.addEventListener("mousemove", (e) => {
  pupils.forEach((pupil) => {
    // get x and y postion of cursor
    var rect = pupil.getBoundingClientRect();
    var x = (e.pageX - rect.left) / 30 + "px";
    var y = (e.pageY - rect.top) / 30 + "px";
    pupil.style.transform = "translate3d(" + x + "," + y + ", 0px)";
  });
});

Keep in mind, you can tweak the divisor to increase/decrease the amount of movement of the eye.

Summary

The final product will be the animated eyes, which follow along with the position of the mouse. Feel free to check out this codepen for the full example:

https://codepen.io/saleh-mubashar/pen/KKBzjdE


Thanks for Reading!