I am currently experiencing some issues when trying to add a click event listener for some foreignObject
s rendered using vanilla JS.
It works when I use the built in d3 on click functions, but I would prefer to have it done using the javascript code.
However, the function never triggers for these elements and I can't understand why.
The code example is not complete, but should highlight what I am trying to do.
var nodes = g.selectAll("foreignObject")
.data(response.nodes)
.enter()
.append("foreignObject")
.attr("x", function(d) {
return d.x - nodeWidth / 2;
})
.attr("y", function(d) {
return d.y - nodeHeight / 2;
})
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.append("xhtml:div")
.attr("class", "outer")
.html(function(d) {
var nodeHtml = createNodeElement(d);
return nodeHtml.outerHTML;
})
// If I append the img like this, it works, but ends up in the wrong "element scope"
.append("img")
.attr("class", "optionsImg")
.attr("src","/images/options-squares.svg")
.on("click", function(d) {
currentTooltipObject = d;
renderTooltipDiv();
});
function createNodeElement(d) {
let nodeElement = document.createElement("div");
nodeElement.className = "nodeElement";
let nodeOptionsImg = document.createElement("img");
nodeOptionsImg.className = "nodeOptionsImg";
nodeOptionsImg.src = "/images/options-squares.svg";
nodeOptionsImg.addEventListener("click", function() {
console.log("Clicked on optionsImg for this object: "+d);
});
nodeElement.appendChild(nodeOptionsImg);
return nodeElement;
}