How to make eyes that follow the mouse in HTML




Code of index.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <title></title>
  </head>
  <body>


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

    <div class="eye">
      <div class="ball"></div>
    </div>
  </div>


<script>
  var balls = document.getElementsByClassName("ball");
  document.onmousemove = function(){
    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";
    //event.clientX => get the horizontal coordinate of the mouse
    //event.clientY => get the Vertical coordinate of the mouse
    //window.innerWidth => get the browser width
    //window.innerHeight => get the browser height

    for(var i=0;i<2;i++){
      balls[i].style.left = x;
      balls[i].style.top = y;
      balls[i].style.transform = "translate(-"+x+",-"+y+")";
    }
  }
</script>

  </body>
</html>

Code of style.css:

body{
    margin: 0;
    padding: 0;
    background: #34495e;
}
.eyes{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 100%;
    text-align: center;
}
.eye{
    width: 240px;
    height: 120px;
    background: #fff;
    display: inline-block;
    margin: 40px;
    border-radius: 50%;
    position: relative;
    overflow: hidden;
}
.ball{
    width: 40px;
    height: 40px;
    background: #000;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    border-radius: 50%;
    border: 15px solid #333;
}

Comentarios

Entradas populares de este blog

How to do an Email Bomber with Python

How to make a Christmas animation in HTML

Chat with Firebase