In a simple webpage, I am trying to get a random cursor image when hover over my element. The curser image needs to change between 4 png files (below for simplicity's sake I used system cursors, this isn't the issue). I'd like the cursor to change every time the user hovers of the element, without having to reload the page.
I'm having trouble creating the random change function. I guess it needs to be javascript or php. I'm not very competent in either and was unsuccessful in googling solutions. Ideas anyone?
I've tried using this as a basis, although here you need to reload to change the cursor, and I'd like the cursor to change without reloading. I've put the javascript in the head under script and it doesn't work -- but works in jsfiddle!! No idea why. I'm not sure how far this is from what I need because of the reloading issue.
Also tried using this php snippet as a basis but did not work at all. Again no idea why.
This is my code without the change in the cursor... super basic I guess
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script>
</script>
</head>
<body>
<div style="background: #ee1; width:300px; height:300px;cursor: help;">
/* I'd like the cursor to change randomally every time the mouse returns to hover over the element. */
/* change between ['help', 'wait', 'crosshair'] */
</div>
</body>
</html>
This is done via JavaScript:
// The array for your cursors
var arrayOfCursors = ['help', 'wait', 'crosshair'];
// Selects the element
var el = document.getElementById('target');
//mouseover event
el.addEventListener("mouseover", function( event ) {
// Changes the cursor to a random from cursors array
el.style.cursor = arrayOfCursors[Math.floor(Math.random() * arrayOfCursors.length)];
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script>
</script>
</head>
<body>
<div id="target" style="background: #ee1; width:300px; height:300px;">
/* The cursor changes randomally every time the mouse returns to hover over the element. */
/* changes between ['help', 'wait', 'crosshair'] */
</div>
</body>
</html>