Elastic Custom Cursor in Vanilla JavaScript

Elastic Custom Cursor in Vanilla JavaScript
Code Snippet:Elastic Custom Cursor Following Mouse (Squeeze and Rotate) w/ JavaScript
Author: Denis Gusev
Published: March 23, 2024
Last Updated: March 23, 2024
Downloads: 795
License: MIT
Edit Code online: View on CodePen
Read More

This code creates an elastic custom cursor in vanilla JavaScript. It follows mouse movements smoothly. It helps enhance user experience on websites.

You can use this code on your website to create a visually appealing and interactive cursor. It adds a unique touch to your site, making it more engaging for visitors. Additionally, it improves user experience by providing smooth and dynamic cursor movements.

How to Create Elastic Custom Cursor in Vanilla JavaScript

1. Start by creating a basic HTML structure. For this tutorial, you only need a single <div> element with a class of “circle” to represent the cursor.

  1. <div class="circle"></div>

2. Define the appearance and behavior of the cursor using CSS. The provided CSS ensures the cursor is circular and positioned correctly.

  1. * {
  2. box-sizing: border-box;
  3. padding: 0;
  4. margin: 0;
  5. }
  6.  
  7. body{
  8. min-height: 100lvh;
  9. background-color: #050908;
  10. }
  11.  
  12. .circle {
  13. --circle-size: 40px;
  14. position: fixed;
  15. height: var(--circle-size);
  16. width: var(--circle-size);
  17. border: 1px solid white;
  18. border-radius: 100%;
  19. top: calc(var(--circle-size) / 2 * -1);
  20. left: calc(var(--circle-size) / 2 * -1);
  21. pointer-events: none;
  22. }

3. Now, let’s make the cursor dynamic with JavaScript. This script tracks mouse movements and applies transformations to the cursor for smooth animation.

  1. /**
  2. * YouTube Tutorial:
  3. * https://youtu.be/wG_5453Vq98
  4. */
  5.  
  6. console.clear();
  7.  
  8. // Select the circle element
  9. const circleElement = document.querySelector('.circle');
  10.  
  11. // Create objects to track mouse position and custom cursor position
  12. const mouse = { x: 0, y: 0 }; // Track current mouse position
  13. const previousMouse = { x: 0, y: 0 } // Store the previous mouse position
  14. const circle = { x: 0, y: 0 }; // Track the circle position
  15.  
  16. // Initialize variables to track scaling and rotation
  17. let currentScale = 0; // Track current scale value
  18. let currentAngle = 0; // Track current angle value
  19.  
  20. // Update mouse position on the 'mousemove' event
  21. window.addEventListener('mousemove', (e) => {
  22. mouse.x = e.x;
  23. mouse.y = e.y;
  24. });
  25.  
  26. // Smoothing factor for cursor movement speed (0 = smoother, 1 = instant)
  27. const speed = 0.17;
  28.  
  29. // Start animation
  30. const tick = () => {
  31. // MOVE
  32. // Calculate circle movement based on mouse position and smoothing
  33. circle.x += (mouse.x - circle.x) * speed;
  34. circle.y += (mouse.y - circle.y) * speed;
  35. // Create a transformation string for cursor translation
  36. const translateTransform = `translate(${circle.x}px, ${circle.y}px)`;
  37.  
  38. // SQUEEZE
  39. // 1. Calculate the change in mouse position (deltaMouse)
  40. const deltaMouseX = mouse.x - previousMouse.x;
  41. const deltaMouseY = mouse.y - previousMouse.y;
  42. // Update previous mouse position for the next frame
  43. previousMouse.x = mouse.x;
  44. previousMouse.y = mouse.y;
  45. // 2. Calculate mouse velocity using Pythagorean theorem and adjust speed
  46. const mouseVelocity = Math.min(Math.sqrt(deltaMouseX**2 + deltaMouseY**2) * 4, 150);
  47. // 3. Convert mouse velocity to a value in the range [0, 0.5]
  48. const scaleValue = (mouseVelocity / 150) * 0.5;
  49. // 4. Smoothly update the current scale
  50. currentScale += (scaleValue - currentScale) * speed;
  51. // 5. Create a transformation string for scaling
  52. const scaleTransform = `scale(${1 + currentScale}, ${1 - currentScale})`;
  53.  
  54. // ROTATE
  55. // 1. Calculate the angle using the atan2 function
  56. const angle = Math.atan2(deltaMouseY, deltaMouseX) * 180 / Math.PI;
  57. // 2. Check for a threshold to reduce shakiness at low mouse velocity
  58. if (mouseVelocity > 20) {
  59. currentAngle = angle;
  60. }
  61. // 3. Create a transformation string for rotation
  62. const rotateTransform = `rotate(${currentAngle}deg)`;
  63.  
  64. // Apply all transformations to the circle element in a specific order: translate -> rotate -> scale
  65. circleElement.style.transform = `${translateTransform} ${rotateTransform} ${scaleTransform}`;
  66.  
  67. // Request the next frame to continue the animation
  68. window.requestAnimationFrame(tick);
  69. }
  70.  
  71. // Start the animation loop
  72. tick();

Finally, integrate the JavaScript code into your HTML file, and you’re ready to go! Feel free to further customize the cursor’s behavior and appearance to suit your website’s design and requirements.

That’s it! You’ve successfully created an elastic custom cursor on your website. Experiment with different properties and add your creative touch to enhance user interaction on your website.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X