Reputation: 247
I want to add 2 icons next to a svg text ( image attached, the node text/name will have diff length ), i know we could use an foreignObject but when using foreignObject i'm not able to get the node values
var addSvgCnt = nodeEnter.append("g")
.attr("class", "txt-swap-parent");
addSvgCnt.append("foreignObject")
.attr("width", 1)
.attr("height", 30)
.append("xhtml:div")
.attr("class", "svg-node")
.html("<img src='https://cdn.onlinewebfonts.com/svg/img_356964.png' height='10' width='10'/>
<span>BRANCH1.2</span>
<img src='https://cdn.onlinewebfonts.com/svg/img_356964.png' height='10' width='10'/>");
here instead of BRANCH1.2 i need the node text, i tried psuedo elements but it's not working either. what is the best solution to achieve this
Upvotes: 0
Views: 1338
Reputation: 13129
Your icon looks so much like this unicode character, you might even replace it and just use tspan
:
Try clicking the nodes to see that clicks are registered correctly.
const someText = "Hi from branch 1";
const circledPlusUnicode = "\u2295";
const x = 50, y = 100;
const text = d3.select("svg")
.append("text")
.attr("x", x)
.attr("y", y);
text.append("tspan")
.attr("class", "circle")
.text(circledPlusUnicode)
.on("click", function() {
console.log("click circle 1");
});
text.append("tspan")
.attr("dy", 2)
.attr("dx", 2)
.text(someText);
text.append("tspan")
.attr("class", "circle")
.attr("dy", -2)
.attr("dx", 2)
.text(circledPlusUnicode)
.on("click", function() {
console.log("click circle 2");
});
.circle {
fill: darkgrey;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
Otherwise, you use getBBox
, which returns a bounding box of the element it's called on, and you can use that to just position the image right next to the text:
const someText = "Hi from branch 1";
const circledPlusImg = "https://cdn.onlinewebfonts.com/svg/img_356964.png";
const x = 50,
y = 100;
const textGroup = d3.select("svg")
.append("g")
.attr("transform", "translate" + [x, y] + ")");
textGroup.append("image")
.attr("class", "circle")
.attr("href", circledPlusImg)
.attr("height", 14)
.attr("width", 14)
.on("click", function() {
console.log("click circle 1");
});
const text = textGroup.append("text")
.attr("dy", 12)
.attr("dx", 16)
.text(someText);
textGroup.append("image")
.attr("class", "circle")
.attr("href", circledPlusImg)
.attr("height", 14)
.attr("width", 14)
.attr("x", function() {
const bbox = text.node().getBBox();
return bbox.x + bbox.width;
})
.on("click", function() {
console.log("click circle 2");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
Upvotes: 1