Change the cursor image (CSS URL) using Javascript

advertisements

I'm currently updating my website. I wanted to have an animated cursor on one of the pages. I found out that modern browsers don't support the .ani format or animated gifs, so I had the idea that I could use the .ani format for older browsers, and for modern browsers have a .png cursor that changes using javascript.

Here's what I tried:

<!DOCTYPE html>
<html>
<head>

<body background="example.gif">

<style type="text/css" id="cursor"> body {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;} </style>

<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("cursor") .body images[x];
}

function startTimer() {
setInterval(displayNextImage, 400);
}

var images = [], x = -1;
images[0] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum1.png'), default;};
images[1] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum2.png'), default;};
images[2] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;};
</script>

<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("test") .src = images[x];
}

function startTimer() {
setInterval(displayNextImage, 400);
}

var images = [], x = -1;
images[0] = "assets/shared/cursors/drum1.png";
images[1] = "assets/shared/cursors/drum2.png";
images[2] = "assets/shared/cursors/drum3.png";
</script>

</head>

<body onload="startTimer()">

<img id=test src="assets/shared/cursors/drum3.png">

<div style="height: 1000px; width: 1000px;"></div>

</body>
</html>

I put the 'test' image in to see if the code worked at all, and sure enough the 'test' image does change as planned, but the cursor just stays at 'drum3.png', not changing. I've tried it many different ways, but can't get it to work.

If possible I'd like to avoid JQuery.

Any help is really appreciated. Thank you!


You can use something like this:

var images = [
  'http://lorempixel.com/21/21/',
  'http://lorempixel.com/22/22/',
  'http://lorempixel.com/23/23/'
];

var x = 0;

function displayNextImage() {
  x = (x === images.length - 1) ? 0 : x + 1;
  document.body.style.cursor = 'url("' + images[x] + '"), default';
}

setInterval(displayNextImage, 400);
html, body {
  height: 100%;
}

body {
  cursor: url('http://lorempixel.com/20/20/'), default;
}