0

Hi all I have created a fully interactive SVG chart that has individual paths that are clickable and rewrite a div with info based on the JSON file I have that matches the id of the path. Currently I am writing this in JQuery but I need to have a function that will add circles onto the path that is clicked. The circles will individually have their own id's and fill that div with info from the object in the JSON that matches the id. I have tried the append method to append a SVG element to the SVG that is loaded into the document but it looks like that might not be the correct way to do it.

This what a section of the SVG looks like before clicked

This is what the goal is to look like after it is clicked

The code I tried was to add a .append() with a template literal of the circle SVG code to add to the path that was clicked. The function would actually append and add to the SVG but it won't render it. This is an example of the code I was using

    function addPath(clickedPath){
    $(clickedPath).append(`
    <circle cx="50" cy="50" r="50" />
    `)
}

function svgLoad(){
    $("#SVG").load("/src/test.svg", function(){
        $("#SVG").css("width", "50vw");
        $("path").on("click", function(evt) {
            addPath($(this));
        })
    }
)}

Is this even possible with Jquery or would this be better in something like React?

JayPee
  • 17
  • 4
  • Please add a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to illustrate at which point your code doesn't work. – herrstrietzel Dec 14 '22 at 14:50
  • Another problem: **you can't nest svg geometry elements**. So you need to insert `` **after** your `` element instead . I've added an example here [jquery's append not working with svg element?](https://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element/74802982#74802982) TL;DR: I strongly recommend switching to plain JS - jquery has quite a lot of issues handling svg. – herrstrietzel Dec 14 '22 at 19:29

1 Answers1

0

It's possible but there are pitfalls with this. You can find some great explanations in here.

Short answer using the following line will solve the issue:

    function addPath(clickedPath){
$(clickedPath).append(`
<circle cx="50" cy="50" r="50" />
`)
 $("body").html($("body").html());

}

But it might cause some issues. If you need something quick and dirty take it, otherwise I would suggest looking into react or vue for something a little more verbose.