52

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Cipher
  • 5,894
  • 22
  • 76
  • 112

4 Answers4

60

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!

other cursor keywords

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:

document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";
div {
  height: 100px;
  width: 1000px;
  background-color: red;
}
<html xmlns="http://www.w3.org/1999/xhtml">

  <body>
    <div>
    hello with a fancy cursor!
    </div>
  </body>

</html>
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
  • I tried this – Cipher Dec 30 '10 at 16:34
  • @user sorry, answer edited. You need to add url('') and put the actual url between the quotation marks. :D – Gordon Gustafson Dec 30 '10 at 20:13
  • Hey! Thanks for help. I changed that but it's still not working for me. Here-> http://textb.in/3a – Cipher Dec 31 '10 at 03:37
20

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. 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';
Brian Ball
  • 12,268
  • 3
  • 40
  • 51
  • This does work, on the premise that the cursor is actually moved, otherwise it remains with existing cursor – s1cart3r Mar 09 '18 at 09:14
15
document.body.style.cursor = 'cursorurl';
Wally Atkins
  • 518
  • 3
  • 11
0

Body may have margin, so better solution will be:

document.documentElement.style.cursor = 'pointer';
puchu
  • 3,294
  • 6
  • 38
  • 62