Search code examples
javascriptcsssvg

How to access and modify a static-served SVG from css / javascript that isn't a part of the DOM?


I'm using an SVG to draw a custom cursor on my website. I need a special animation to be played on click, and to do that I need to be able to edit properties inside the SVG. Hence the question: Is it possible to do it? How do I query the element and change it?

Neither query selector nor document.findByID worked, because a cursor is not a part of the DOM. Modifying the SVG on the backend isn't a solution as well, because it won't update real-time. I could just fetch an SVG from a static URL, but I can't change it, can I? I have tried multiple ways to do it, and it doesn't work.


Solution

  • If you utilize SVG as a CSS cursor or as an image source, you won't be able to modify the SVG from your website's JavaScript or CSS because these SVGs are not part of the in-browser DOM.

    A possible workaround for this, you might use a pure JavaScript cursor following the mouse position with an SVG inside. You can then manipulate that SVG from the JavaScript as much as you want it.

    Ex:

    HTML

    <div id="customCursorSvg">
        <svg fill="#000000" xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 24 24" width="64px" height="64px">
            <path d="M 4,8 L 4,3 12,11 z"/>
        </svg>
    </div>
    

    CSS

    /* CSS */
    #customCursorSvg {
        position: absolute;
        pointer-events: none;
        transition: all 0.2s ease;
        transform: translate(-50%, -50%);
        z-index: 9999;
    }
    

    JavaScript

    /* JavaScript */
    const cursorSvg = document.getElementById('customCursorSvg');
    window.addEventListener('mousemove', e => {
        cursorSvg.setAttribute('style',`top: ${e.pageY}px; left: ${e.pageX}px;`);
    });
    
    window.addEventListener('click', () => {
        // Animation or property change on click
        cursorSvg.firstChild.style.fill = "red";
    });