I wanted to use a script to change the mouse pointer on my website using JavaScript. It's better done by CSS but my requirement is of a script that can be distributed to many people to embed in the head section of their websites. Through CSS, this can be manipulated by
html
{ cursor: *cursorurl*
}How to do the same in JavaScript?
5 Answers
Javascript is pretty good at manipulating css.
document.body.style.cursor = *cursor-url*; //OR var elementToChange = document.getElementsByTagName("body")[0]; elementToChange.style.cursor = "url('cursor url with protocol'), auto";or with jquery:
$("html").css("cursor: url('cursor url with protocol'), auto");Firefox will not work unless you specify a default cursor after the imaged one!
Also remember that IE6 only supports .cur and .ani cursors.
If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:
// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);working sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">
div { height: 100px; width: 1000px; background-color: red;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('), auto";
</script>
</html> 3 Look at this page: . Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.
document.body.style.cursor = 'wait'; 1 document.body.style.cursor = 'cursorurl'; 0 Just do document.documentElement.style.cursor = "my-cursor-here". This changes the cursor even in locations where there are no elements (unlike document.body, which only works for places with elements).
Note: This may not work when your mouse if over some elements, such as <button>.
With regards to @CrazyJugglerDrummer second method it would be:
elementsToChange.style.cursor = ""; 0