Change the cursor with Javascript
Posted November 12th, 2009 in Javascript
This post shows how to change the cursor on a web page with Javascript by assigning a value to the document.body.style.cursor property.
Assign a value to document.body.style.cursor
Assign one of the cursor properties to document.body.style.cursor to change the cursor (refer to my earlier post titled CSS cursor property for a list of cursor properties.). The first example below will change the cursor to an hourglass:
document.body.style.cursor = "wait";
The second example restores it back again by assigning "default" to the cursor property:
document.body.style.cursor = "default";
Working Example
The following select box and button can be used to change the cursor. If you are viewing this post in an RSS reader you will probably need to click through to view this in a web browser for the example to work.
Example Code
Here's the code behind the example above:
<script language="Javascript">
function example_change_cursor() {
document.body.style.cursor = document.getElementById('example-cursor').options[document.getElementById('example-cursor').selectedIndex].value;
}
function example_restore_cursor() {
document.body.style.cursor = 'default';
}
</script>
<select id="example-cursor">
<option>default</option>
<option>crosshair</option>
<option>e-resize</option>
<option>help</option>
<option>move</option>
<option>n-resize</option>
<option>ne-resize</option>
<option>nw-resize</option>
<option>pointer</option>
<option>progress</option>
<option>s-resize</option>
<option>se-resize</option>
<option>sw-resize</option>
<option>text</option>
<option>w-resize</option>
<option>wait</option>
</select>
<input type="button" onclick="example_change_cursor()" value="Change Cursor" />
<input type="button" onclick="example_restore_cursor()" value="Restore Default" />
Related posts:
- jQuery: Mouse co-ordinates within the element when mouseover or click an element (Wednesday, October 28th 2009)
- Get the mouse co-ordinates with jQuery when an element is clicked (Friday, October 9th 2009)
- Get the mouse co-ordinates with jQuery (Tuesday, October 6th 2009)
- CSS cursor property (Saturday, September 5th 2009)

Comments
blog comments powered by Disqus