Skip to content
Related Articles

Related Articles

Improve Article

Snake Like Effect using CSS and JavaScript

  • Difficulty Level : Expert
  • Last Updated : 19 Feb, 2021

In this article, we will see how to create a Snake Like Effect by using CSS and JavaScript.

CDN Link: Include the following GSAP library in your HTML code.

<script src=”https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js”></script>

Approach :

  • We have taken a div tag named snake which is an instance of the full snake. We have taken circle, we can take another shape by using simple CSS.
  • We have created more divs to give the length of the snake. We can include more div tags to increase its length.
  • document.body.addEventListener(“mousemove”): This function in JavaScript attaches a moving mouse event to the document. When the user moves the mouse pointer anywhere in the document, the event which is being mentioned occurs.
  • e.clientX: Get the horizontal coordinate.
  • e.clientY: Get the vertical coordinate.
  • stagger :For delay in animation (0.05 sec),  we can see the snake.
  • gsap.to(“.snake”): It will track the snake with reference to pointer coordinates.

Example:

HTML






<!DOCTYPE html>
<html>
<head>
      
    <style type="text/css">
        /* Area part for snake */
        .area
        {
            width: 80px;
            height: 80px;
            position: relative;
        }
        /* Designing of a part of snake (here circle) */
        .area .snake
        {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgb(3, 171, 15);
            border: 2px soild white;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div class="area">
        <!-- You can add more divs for a long snake-->
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
        <div class="snake"></div>
    </div>
  
<!-- GSAP Library -->
<script 
</script>
  
<!-- JavaScript Code for mouse event -->
<script type="text/javascript">
    document.body.addEventListener("mousemove", e => {
        gsap.to(".snake", {
            x : e.clientX,
            y : e.clientY,
            stagger : -0.05,
        })
        })
</script>
</body>
</html>


Output : 

As you can see from the above output, we have created a snake that follows our mouse pointer making it look like a Snake-like effect.

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :