In this tutorial, we will learn to hide the cursor in a web page using CSS and JavaScript. Sometimes, we need to create a styled cursor and then need to hide the cursor. Maybe it's also necessary to hide the cursor for specific HTML elements.
There are two ways to hide the cursor on a web page. One uses CSS and the other uses JavaScript. We will learn both methods one by one in this tutorial.
CSS Allows us to change the style of the cursor. We can create different types of cursors using CSS. If we don't want to show the cursor, we can apply the style "cursor: none" to a specific HTML element.
Users can hide the cursor using CSS according to the following syntax.
CSS Selector { cursor: none; }
In this example, we created the div element and specified the correct height and width. Additionally, we apply a red background color to the div using CSS. After that, we add the class attribute to the div element and initialize it with the "test" value.
We use the test class name as a CSS selector in CSS and apply the "cursor: none" style to the div element.
<html> <head> <style> .test { /* style to hide the cursor */ cursor: none; height: 300px; width: 300px; background-color: red; } </style> </head> <body> <h2> Hiding the cursor using <i> CSS. </i> </h2> <!-- hiding the cursor in this div element --> <div class="test">Hiding the cursor for this div.</div> </body> </html>
In the above output, the user can observe that the cursor disappears when the user moves the cursor into the div element.
We can use JavaScript to change the style of any HTML element. Each HTML element contains a style attribute, which we can access by passing the HTML element as a reference. Afterwards, we can access the specific style property of the style attribute and change its value. Here we will use JavaScript to change the value of the cursor attribute to none.
Users can use JavaScript to hide the cursor on a web page according to the following syntax.
let testDiv = document.getElementById("test"); testDiv.style.cursor = "none";
In the above syntax, style is the attribute of the testDiv element, and the cursor is the attribute of the style object. We change the value of the cursor property to "none".
In the example below, we access the HTML div element via the id in the