Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #css #HowTo

How to Change Cursor to Image on Hover Using CSS & JavaScript

In this article, you'll learn how to change the cursor to an image when hovering over an element using CSS and JavaScript.

Method 1: Using CSS url Property #

When you want to change the cursor to a custom image, you can do it with CSS. First, create the cursor image you want to use and save it as a .png or .gif file. Then, you can apply it to an element's hover state using the url property.

<style>
  .custom-cursor {
    cursor: url('custom-cursor.png'), auto;
  }
</style>
  1. The .custom-cursor class sets the cursor style for elements with this class.
  2. cursor: url('custom-cursor.png'), auto; changes the cursor to the custom image custom-cursor.png on hover and falls back to the default cursor when not hovering.

Method 2: Using JavaScript for Dynamic Cursor #

In some cases, you might want to dynamically change the cursor based on user interactions. JavaScript can help achieve this by listening to events and updating the cursor style.

<button id="my-btn">Custom Cursor</button>
<script>
  const element = document.getElementById('my-btn');

  element.addEventListener('mouseenter', () => {
    element.style.cursor = 'url("https://app.3schools.in/logo.png"), auto';
  });

  element.addEventListener('mouseleave', () => {
    element.style.cursor = 'auto';
  });
</script>
  1. We use JavaScript to select the element we want to add the custom cursor to.
  2. When the mouse enters the element, we set the cursor to ../logo.png.
  3. When the mouse leaves, we revert to the default cursor.

Conclusion #

In this article, you've learned two methods to change the cursor to an image on hover. Whether you prefer a simple CSS approach or dynamic cursor changes with JavaScript, you can create engaging user experiences that make your website stand out.

save
listen
AI Answer
Write Your Answer
loading
back
View All