Open In App

How To Change The Cursor On Hovering In CSS?

Last Updated : 09 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Changing the cursor style when a user hovers over a particular element is a common user experience enhancement in web development. The default cursor is usually a pointer (arrow) but CSS allows us to change the cursor to various shapes such as a hand (for links), text selection, or even custom icons.

Prerequisites

These are the approaches for changing the cursor on hovering in CSS:

Using CSS Cursor Property

In this approach, we will use the CSS cursor property which is the simplest and most common way to change the cursor style. This property allows us to define the appearance of the cursor on hover, such as changing it to a pointer, crosshair, or wait symbol.

Example: In this example, we are using the CSS cursor property to change the cursor on hovering in CSS. In this, there are three types of text having three different ways of hovering.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
     content="width=device-width,
      initial-scale=1.0">
    <title>Cursor Property</title>
    <style>
        .pointer {
            cursor: pointer;
        }

        .text {
            cursor: text;
        }

        .move {
            cursor: move;
        }

        h3 {
            color: green;
        }
    </style>
</head>

<body>
    <h3>Welcome to 
        GeeksForGeeks</h3>
    <div class="pointer">
    Hover over me for pointer cursor</div>
    <div class="text">
    Hover over me for text cursor</div>
    <div class="move">
    Hover over me for move cursor</div>

</body>

</html>

Output:

a1
Output using CSS Cursor Property

Changing Cursor with JavaScript

In this approach we will use change the cursor style dynamically using JavaScript. This method is useful when we want to change the cursor based on some user interaction or event.

Example: In below example we are changing the cursor style dynamically using the JavaScript. In this, the way in which the text is being hovered gets changed.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
     content="width=device-width,
      initial-scale=1.0">
    <title>JavaScript Cursor</title>
</head>

<body>

    <div id="jsCursor">Hover over
         me to change cursor</div>

    <script>
        const div = document.
        getElementById('jsCursor');
        div.addEventListener
        ('mouseover', function () {
        div.style.cursor = 'crosshair';
        });
        div.addEventListener
        ('mouseout', function () {
        div.style.cursor = 'default';
        });
    </script>

</body>

</html>

Output:

a1
Output of Changing Cursor using JavaScript

Next Article
Article Tags :

Similar Reads