mmangual83
mmangual83

Reputation: 151

How to implement custom cursor

I have a class that is in charge of changing the mouse cursor when it hovers over a specified element. It takes a string as a parameter which is the relative path where I am keeping my custom cursor (it is .png by the way). But when I run the web site it only shows the regular pointer. Why is that? What am I doing wrong here?

Here is the code I am working with:

        /*
         * True if the mouse has entered the object
         */
        private _hasEntered: boolean = false;

        /*
         * The file name
         */
        private _fileName: string = "";

        constructor(fileName: string) {
            this._fileName = fileName;
        }

        /*
         * Initializes class
         */
        public awake(): void {
            //...Code to handle mouse enter/exit events goes here
        }

        /**
         * Called when the mouse has entered this object
         */
        private _onMouseEnter(): void {
            document.body.style.cursor = this._fileName;
            this._hasEntered = true;
        }

Upvotes: 1

Views: 100

Answers (2)

realbart
realbart

Reputation: 4004

First of all, you usually are better of just setting the cursor property on the item being hovered like so:

img.specialpointer {
    cursor: url(pics/specialcursor.png), auto;
}

BTW: this overrides behavior set on the body. I'm not sure IMG has a cursor-property by default. If this is the case, the body cursor is ignored.

Secondly, I'm not sure you're setting your cursor property correctly. It might be something like

document.body.style.cursor = 'url(' + this._fileName + '), auto';

Thirdly, do realize custom cursor images are not supported by every browser.

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116180

A file name is actually a URL and should be specified as such. Try

document.body.style.cursor = 'url(' + this._fileName + ')';

Upvotes: 2

Related Questions