How to Change the Mouse-Over Cursor in JavaScript
The "cursor" property in Cascading Style Sheets (CSS) code allows you to change the way the user's mouse cursor will appear when it's pointing to an element on your Web page. You can specify different cursors for different elements to help build a nuanced user interface, or you can change the cursor property for the "body" element to change the cursor for the whole page. JavaScript can be used to declare and change CSS properties, so you can dynamically reassign the "cursor" property for various elements on the page.
Instructions
-
-
1
Place the following code between the "head" tags of your HTML document:
<script type="text/javascript">
function changeCursorById(ref,cur){
document.getElementById(ref).style.cursor = cur;
}
</script>
-
2
Add the following code to the body of your HTML document to see how the function works:
<input type="button" id="bu1" value="Change Cursor" onClick="changeCursorById('bu1','crosshair');" />
The button produced will change its own "cursor" property when clicked. The value of the "id" attribute is used to identify the element to the function.
-
-
3
Use any of the following values for the "cursor" property: "help," "move," "pointer," "progress," "text," "wait," "crosshair," "n-resize," "ne-resize," "e-resize," "se-resize," "s-resize," "sw-resize," "w-resize," and "nw-resize." You can also use "auto," "default," and "inherit." If you choose "auto," the cursor the browser would normally use for that element is assigned. If you choose "default," the regular arrow cursor is used. An example of the distinction is that if you assign "default" to a "p" tag, the cursor will not change to an i-beam as it normally would over that paragraph, but will remain as the default arrow. "Inherit" assigns the same cursor to the element as its parent element (the tag it's nested within).
-
4
Change the cursor to a custom image like this:
changeCursorById('bu1','URL(customcursor.cur)');
Cursor images must be stored on the server as either "cur" or "ani" files.
-
5
Use the following function to change the cursor property for all the elements of one kind in a page:
function changeCursorByTagName(tag,cur){
for(var i = 0;i < document.getElementsByTagName(tag).length;i++){
document.getElementsByTagName(tag)[i].style.cursor = cur;
}
}
Use a tag name, like "p," instead of an ID.
-
1