简体   繁体   中英

External, dynamically loaded SVG: Can't access Elements with JavaScript

I am programming a digital advent calendar for a client. This thing where you can open a little door every day until christmas. Here is my problem: I have 24 svgs where every day one more door is open and you can click on "todays" door to open it. So i have overlays in the svgs which trigger a modal where the content is dynamically loaded.

Also the SVG itselfs needs to be dynamically loaded since it is a new one every day. When i run it locally everything works fine but i need to implement it into the customers Webflow.com environment. The svgs are stored on my own server. As soon as i load it in the webflow environment i cannot access the elements inside the svg anymore. I guess this is because it is not loaded into the DOM properly. I can't find any solution.

So this is the code block that i embed into the webflow page:

<div class="backgroundcontainer">
    <object class="backgroundimage" data="" id="background" type="image/svg+xml"></object>
</div>

then via javascript i add the image:

let bgImage = document.getElementById('background');
if (bgDay >= 25) {
    bgImage.data = "MYSERVER/assets/images/bg/25.svg"
} else {
    bgImage.data = "MYSERVER/assets/images/bg/" + bg;
}

bg is "today".svg

locally this works to add the click listener to the 24 "doors" (with ids 1-24 within the svg) which are defined in the svg:

bgImage.addEventListener('load', function () {
    let bgContent = bgImage.contentDocument;

    for (let i = 1; i <= today; i++) {
        let door = bgContent.getElementById(i);
        door.style.cursor = 'zoom-in';
        door.setAttribute('id', i.toString())
        door.addEventListener('click', function () {
            openModal(i)
        })
    }
})

in webflow bgImage.contentDocument returns null

any ideas? Thanks

It doesn't matter where your SVGs are hosted. Referencing them dynamically is also not an issue, however I've not seen <object> used for this purpose before.

In your case, I'd build out the Webflow site with all of the components you want, and use a standard Image element, with an id eg background .

Then your button click script updates the img src URL and opens the modal.

Note your use of the word "background" is a bit mystifying, since it suggests you're trying to set a background image- which is a style attribute. The approach here would be similar, but with some variations to your script.

Also...

i cannot access the elements inside the svg anymore

If you mean that you're seeing the SVG successfully, but unable to access the inner structure of the SVG for eg class based CSS coloring, then the problem is that the SVG must be inline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM