How to create custom cursor | Flag Cursor

Hello, guys in this tutorial we will create a custom cursor using HTML CSS & JavaScript.

First, we need to create two files index.html and style.css then we need to do code for it.

Custom Cursor Step:1

Add below code inside index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>How to create custom cursor</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta https-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="custom-cursor"></div>

    <script type="text/javascript">
      const cursor = document.querySelector('.custom-cursor');

      window.addEventListener("mousemove", event => {
        let x = event.pageX - (cursor.offsetWidth / 2),
            y = event.pageY - (cursor.offsetHeight / 2);

            cursor.style.left = `${x}px`;
            cursor.style.top = `${y}px`;
      });

      window.addEventListener("mousedown", event => {
        if (!cursor.classList.contains('click')) {
          cursor.classList.add("click");

          setTimeout( () => {
            cursor.classList.remove("click");
          }, 300)
        }
      });  
      
    </script>
  </body>
</html>

Custom Cursor Step:2

Then we need to add code for style.css which code i provide in below screen.

* {
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
	height: 100vh;
	background-color: #000;
	cursor: none;
}

.custom-cursor {
    position: absolute;
    left: 0;
    top: 0;
    width: 35px;
    height: 35px;
    background: url(flag-waving.png) no-repeat center/cover;
}

.custom-cursor.click {
	transform: scale(1.3);
}

Custom Cursor Output:

Leave a Comment