DEV Community

Cover image for custom cursor javascript
Stackfindover
Stackfindover

Posted on • Updated on

custom cursor javascript

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

Profile card design HTML & CSS
Snake border animation CSS

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 http-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>
Enter fullscreen mode Exit fullscreen mode

Disable Right Click Using JavaScript

Custom Cursor Step:2

Then we need to add code for style.css which code I provide in the 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);
}
Enter fullscreen mode Exit fullscreen mode

Animated Stars With Realistic Moon
Advanced Animated Submenu

Custom Cursor Output:

Custom Cursor CodePen Output:

Top comments (0)