kaalobaadar
kaalobaadar

Reputation: 429

Create a close button on a svg using d3.js

I am new to d3.js and I have a requirement of creating a close button [x] on the top right corner of a rect. On clicking the button the rect should be removed from the chart.
I am considering to use svg remove as suggested in the linked content.
I am currently using the letter X as the close button. This implementation however seems not to work the letter is not visible (despite of appearing on the DOM).

bl.ocks link here: http://bl.ocks.org/bhandarisumit/b48e134e358f94a290a2

Code:

var margin = {top: 15, right: 40, bottom: 20, left: 50},
    width = 960 - margin.left - margin.right,
    height = 240 - margin.top - margin.bottom;


var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");


var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", "0")
.attr("y", "0")
.attr("width", width)
.attr("height", height);

var chartBody = svg.append("g")
.attr("clip-path", "url(#clip)");

var rect = chartBody.append('svg:rect')
.attr('width', width-20)
.attr('height', height-20)
.attr('fill', 'white');


var labeledRect = chartBody.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", height-20)
.attr("width", width-20)
.style("stroke", "red")
.attr("class", "labelbox")
.style("fill", "none");

var closeArea = chartBody.append('text')
.text('X')
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
labeledRect.append('text').attr('color','black').text('X');
body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

rect {
  fill: #fff;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.js"></script>

Upvotes: 0

Views: 2506

Answers (1)

toshi
toshi

Reputation: 2897

The letter 'X' is placed out of the area of 'rect' element, so it is not visible.
The 'text' element has 'x' and 'y' attributes(default 0) for its position,
but the coordinate indicates the position of left-bottom corner of the text.
So if you don't set 'y' attribute, text is not visible, because 'y' is 0.
I inserted a line .attr("y", 20) into your code. Please try this.

var closeArea = chartBody.append('text')
.text('X')
.attr("y", 20)
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");

Alternative solution is using dominant-baseline attribute like this:

var closeArea = chartBody.append('text')
.text('X')
.attr("dominant-baseline","text-before-edge")
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");

Upvotes: 1

Related Questions