Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript Cursor property
The JavaScript cursor property sets or returns the cursor type that will be displayed when hovering over an element. This property allows you to change the mouse cursor appearance dynamically using JavaScript.
Syntax
element.style.cursor = "cursorType";
Example: Changing Cursor on Button Click
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
padding: 20px;
background-color: #f0f0f0;
margin: 10px 0;
border: 2px solid #ccc;
}
.Btn {
padding: 10px 15px;
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>JavaScript Cursor Property</h1>
<p class="sample">Hover over this paragraph to see cursor changes</p>
<h3>Click buttons to change cursor type:</h3>
<button class="Btn" onclick="changeCursor('crosshair')">Crosshair</button>
<button class="Btn" onclick="changeCursor('pointer')">Pointer</button>
<button class="Btn" onclick="changeCursor('grab')">Grab</button>
<button class="Btn" onclick="changeCursor('default')">Default</button>
<script>
let sampleEle = document.querySelector(".sample");
function changeCursor(cursorType) {
sampleEle.style.cursor = cursorType;
console.log("Cursor changed to: " + cursorType);
}
</script>
</body>
</html>
Common Cursor Types
| Cursor Value | Description | Use Case |
|---|---|---|
default |
Standard arrow cursor | Normal elements |
pointer |
Hand with pointing finger | Clickable links/buttons |
crosshair |
Cross-shaped cursor | Selection tools |
grab |
Open hand | Draggable elements |
text |
I-beam cursor | Text input areas |
Dynamic Cursor Example
<!DOCTYPE html>
<html>
<head>
<style>
.hover-area {
width: 200px;
height: 100px;
background-color: lightblue;
border: 2px solid blue;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div class="hover-area" id="hoverDiv">Hover over me!</div>
<script>
const hoverDiv = document.getElementById('hoverDiv');
hoverDiv.addEventListener('mouseenter', function() {
this.style.cursor = 'grab';
this.textContent = 'Grab cursor active';
});
hoverDiv.addEventListener('mouseleave', function() {
this.style.cursor = 'default';
this.textContent = 'Hover over me!';
});
</script>
</body>
</html>
Key Points
- The cursor property only affects the appearance, not the functionality
- Changes are immediate and don't require page refresh
- CSS cursor property can also be used for static cursor changes
- JavaScript provides dynamic control based on user interactions
Conclusion
The JavaScript cursor property provides an easy way to enhance user experience by changing cursor appearance dynamically. Use appropriate cursor types to give visual feedback about element functionality and interactivity.
Advertisements
