wtrmeln
wtrmeln

Reputation: 131

JQuery Event on SVG not firing

I have a problem with events. I have a div, inside which I have an svg area. On that area I want to place some nodes in some groups. I need a different behaviour for when I click on an empty area and and a different one for when I click on the svg rectangle.

The thing is, only my div contextmenu event is firing. My JS:

$(function() {

$('#mainBoard').on("click", function (ev) {
    ev.preventDefault();
    $('body').append("DivEventTiggered ");
    return false;
});

$("svg").find("g.node").find("rect").on("click", function (ev) {
    ev.preventDefault();
    $('body').append("SVGEventTriggered");
    return false;
})

$('#add-svg').click(function (ev) {
        d3.select("#SVGcanvas")
        .append("g")
        .attr("id", "id0")
        .attr("class", "node")
        .append("rect")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", 40)
        .attr("height", 40)
        .style("fill", "purple")
        .style("opacity", "0.1")
        .style("border", "1px black solid");
    return false;
})
})

CSS:

#mainBoard {
padding: 0;
margin: auto;
display: block;
width: 200px;
height: 200px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
border: 1px solid black;
}

#menu {
height: 37px;
}

And my HTML snippet

<div id="mainBoard">
<svg id="SVGcanvas" style="height:inherit; width:inherit; display:block;"></svg>
<div id="menu">
    <button id="add-svg" class="btn btn-success" style="margin-right: 10px;">Add SVG</button>
</div>

Here you can see that only Div Event is triggered: JSFiddle

Upvotes: 2

Views: 1215

Answers (1)

DevGrowth.Tech
DevGrowth.Tech

Reputation: 1563

The problem is that you are binding click event to svg rectangles before they exist (by clicking the add svg button).

The simplest solution would be:

$('#add-svg').click(function (ev) {
        d3.select("#SVGcanvas")
        .append("g")
        .attr("id", "id0")
        .attr("class", "node")
        .append("rect")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", 40)
        .attr("height", 40)
        .style("fill", "purple")
        .style("opacity", "0.1")
        .style("border", "1px black solid");

         // now the g node exists
         $("svg").find("g.node").find("rect").on("click", function (ev) {
            ev.preventDefault();
            $('body').append("SVGEventTriggered");
            return false;
        })
    return false;
})

Upvotes: 2

Related Questions