Search code examples
jquerysvgcursor

SVG url cursor not changing cursor


Here is the code:

 var svgUrl = "url('" + 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"' +
              ' version="1.1" width="32" height="32"><circle cx="16" cy="16" r="16" ' +
              ' style="fill: red;"/></svg>' + 
              "'), auto;";

This does not work:

 $("body").css('cursor', svgUrl);

This works as expected:

 $("body").css('cursor', "wait");

I tried to insert the SVG tag to render it as plain HTML and it does render a circle so I think the SVG markup is OK. I split the svgUrl line to make it more readable. I have narrowed the issue and provided simple code to resolve the main problem. In the application, the cursor will change dynamically...

EDIT after accepting answer:

The accepted answer resolves the question asked. However, I am wondering why, if I used the string provided in the answer, this does not work?

    var theCursor = "url(\"" + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'" +
                    " version='1.1' width='32' height='32'%3E%3Ccircle cx='16' cy='16' r='16'" +
                    " style='fill: blue;'/%3E%3C/svg%3E\"), auto;";

    $("body").css('cursor', theCursor);

Solution

    1. I've rewritten the cursor rule keeping your concatenation. Please note that some quotes are escaped.

    2. To make it work I'm creating a new <style> element in the <head> and I'm setting the textContent = theCursor;

    var s = document.createElement("style");
    document.head.appendChild(s);
    
    let theCursor = "body{cursor: url(\"" + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'"
    +
        " version='1.1' width='32' height='32'%3E%3Ccircle cx='16' cy='16' r='16'" + 
        " style='fill: blue;'/%3E%3C/svg%3E\"), auto;}";
    
    s.textContent = theCursor;
    body{
      height:100vh;
     /* 
      cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' width='32' height='32'%3E%3Ccircle cx='16' cy='16' r='16' style='fill: red;'/%3E%3C/svg%3E"), auto;}
      */
      
    }
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="32" height="32">
      <circle cx="16" cy="16" r="16"  style="fill: red;"/>
    </svg>