Animated Eyes Follow Mouse Cursor Using Only HTML, CSS And JavaScript


Eyes Follow Mouse Cursor Using Only HTML, CSS And JavaScript


Eyes Follow Mouse Cursor Using Only HTML, CSS And JavaScript


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>
</body>
</html>

CSS

<Style>
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;
}
</Style>

JavaScript


<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>


VIDEO








Post a Comment

Previous Post Next Post