Snake Like Effect using CSS and JavaScript
Last Updated :
05 May, 2025
Improve
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:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
/* Area part for snake */
</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
src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js">
</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>
.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 solid white;
border-radius: 50%;
}
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.