javascriptcssimagecursorsetattribute

JS Change the cursor for an image stored in a variable


Is it possible to change the cursor with a customized image stored in a variable?

I have tried setAttribute or .style.cursor, but it does not seems to work..

Here are some examples of what I have tried:

var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").style.cursor = MyImage;

I also tried:

var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").setAttribute("cursor", MyImage);

The idea is that the var MyImage may change depending on some actions by the user.

I know Firefox requires a second cursor option, but I do not know how to do it with a variable.


Solution

  • There are a couple of problems with the code given.

    The image definition needs to be not only a string, but also a url.

    Also, a fallback is mandatory (not just required by Firefox).

    See MDN for more detail on what is allowed.

    let MyImage = 'https://i.sstatic.net/LZ9aI.png';
    document.getElementById("DivWithMouseOverEvent").style.cursor = 'url(' + MyImage + '), grab';
    #DivWithMouseOverEvent {
      width: 50vw;
      height: 50vh;
      background: cyan;
    }
    <div id="DivWithMouseOverEvent"></div>