Escher
Escher

Reputation: 5795

How to fill dynamically-created SVGs (checking DOM is updated)

I have some inline svgs with paths of class "paintstroke". I insert them as part of a larger function, and then I wish to fill them afterwards. The trouble is, I don't think the DOM is ready at the time this code is called (immediately after the svg creation), so nothing happens.

var paths = document.getElementsByClassName("paintstroke");
for(var i = 0; i < paths.length; i++){
    paths[i].style.fill = colors[i];
}

If I do a setTimeout before calling the above block it generally works, but occasionally misses a few svgs and is obviously a hacky solution. How can I check that all my .paintstroke objects are ready before trying to fill them?

Upvotes: 1

Views: 56

Answers (1)

rnrneverdies
rnrneverdies

Reputation: 15667

How can I check that all my .paintstroke objects are ready before trying to fill them?

You can use the old DOMNodeInserted event: Jsfiddle

document.addEventListener('DOMNodeInserted', function (event) {
    if (event.target.classList.contains("paintstroke")) {
        // do the trick here.
    }
});

Please note that this solution will not work on IE < 10

UPDATE: based on comments, a working example with SVG

Upvotes: 2

Related Questions