Question

I need a way of changing the mouse-cursor on a html-page. I know this can be done with css, but I need to be able to change it at runtime, like for instance having buttons on the page, and when they're clicked they change the cursor to a specific custom graphic. I think the best (or only?) way of doing this is through javascript? I hope there's a way of doing this nicely that will work on all of the major browsers. I would be very grateful if someone could help me with this.

Thanks in advance

Was it helpful?

Solution

Thanks for the replies. I finally got it working. Here's how I did it:

<html>
<head>
    <script type="text/javascript">
        function changeToCursor1(){
            document.body.style.cursor="url('cursor1.ani'),url('cursor1.cur'), default";
        }
        function changeToCursor2(){
            document.body.style.cursor="url('cursor2.ani'),url('cursor2.cur'), default";
        }
    </script>
</head>

<body>

    <form>
        <input type="button" value="Change to cursor 1" onclick="changeToCursor1()" /><br>
        <input type="button" value="Change to cursor 2" onclick="changeToCursor2()" />
    </form>
</body>

I found out that to get it to work in Firefox you must pass at least 2 choices of cursors, e.g. cursor="url('cursor1.cur'), default" Or else it wont work. Also, in Firefox it doesn't work with ani-cursors, only cur. Which is why I've put a cur after ani. The ani will show up in IE, the cur in Firefox.

Does anyone know if it's possible to change the cursor in IE without the active-X warning showing up and the user having to accept?

OTHER TIPS

It's easy if you want to do this on Links only. There you have some CSS like this:

a:hover { cursor: crosshair; } #this is when you mouseover the link
a:active { cursor: wait; } #this is the moment you click it

Since :active won't work for other Elements than a, you may want to use the Javascript stated by Prestaul and scunliffe.

Using JQuery:

$('.myButton').click(function(){
    $(this).css('cursor', 'url(/url/to/cursor/image)');
});
//you can set all the normal cursors like this
someElem.style.cursor = 'progress';

What is the special cursor you want?... maybe there is a better option.

// Get the element you want to change the cursor for
var el = document.getElementById('yourID');

// This image url is relative to the page url
el.style.cursor="url(pathToImage.png)";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top