Reputation: 163
How to change the existing html text in a D3 rect to something else on the click of a button. There is an image on the top right corner of a D3 rect. When I click on that image the text inside the rect has to change to another html text like This is new text . It would be great if anyone could help me figure out a way to do it.
<!DOCTYPE html>
<html>
<head>
<!-- <script
data-require="[email protected]"
data-semver="3.5.3"
src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"
></script> -->
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr('y'),
x = text.attr('x')
dy = parseFloat(text.attr('dy')),
tspan = text
.text(null)
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', dy + 'em');
while ((word = words.pop())) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(' '));
line = [word];
tspan = text
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', ++lineNumber * lineHeight + dy + 'em')
.text(word);
}
}
});
}
var svg = d3
.select('body')
.append('svg')
.attr('width', 500)
.attr('height', 5000);
// var longText =
// 'This is very very long text. This is very very long text. This is very very long text. This is very very long text. This is very very long text. This is very very long text.';
var longText =
'<span>This is very very long textThis is very very long textThis is very very long textThis is very very long text</span>';
var totHeight = 0;
drawRect();
function drawRect() {
//var someWidth = randomIntFromInterval(40, 300);
var someWidth = 212;
var g = svg
.append('g')
.attr('transform', 'translate(20,' + totHeight + ')');
var rect = g
.append('rect')
.style('fill', 'steelblue')
.attr('x', 50)
.attr('y', 50)
.attr('width', someWidth)
.attr('height', 1);
var txt = g
.append('text')
.html(longText)
.attr('x', 70)
.attr('y', 70)
.attr('dy', '.71em')
.style('fill', 'black')
.call(wrap, someWidth - 28);
var img = g.append('svg:image')
.attr('x', 250)
.attr('y', 40)
.attr('width', 24)
.attr('height', 24)
.attr(
'xlink:href',
'./img/edit-24-px.svg'
);
img.on('click', function () {
//d3.append('text').html("<span> bye </span>");
console.log('hi');
});
var height = txt.node().getBBox().height + 25;
totHeight += height + 10;
rect.attr('height', height);
}
</script>
</body>
</html>
https://jsfiddle.net/passionateCoder/prh2acot/
I am not able to add an image to the JSFiddle.
Upvotes: 0
Views: 746
Reputation: 484
This should work.
img.on('click', function () {
txt.text('this is new text')
});
Or for innerHTML:
img.on('click', function () {
txt.html('this is new text')
});
Remember that you cannot use traditional HTML in SVG Texts. Read here: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text
Upvotes: 1