D3 Column Chart Click Event

by falsy

HTML

<!doctype html>
<html lang="ko">
  <head>
    <title>D3.js Custom bar chart</title>
  </head>
  <body>
    <div id="svg-area"></div>
  </body>
</html>

JavaScript

const width = 400;
const height = 400;
const margin = {top: 40, left: 40, bottom: 40, right: 40};
const baseColor = '#dddddd';
const pointColor = '#7ab8aa';

const data = [
    {name: 'A', value: 10},
    {name: 'B', value: 29},
    {name: 'C', value: 32},
    {name: 'D', value: 25},
    {name: 'E', value: 23},
    {name: 'F', value: 15}
  ];

const x = d3.scaleBand()
  .domain(data.map(d => d.name))
  .range([margin.left, width - margin.right])
  .padding(0.4);

const y = d3.scaleLinear()
  .domain([0, d3.max(data, d => d.value)]).nice()
    .range([height - margin.bottom, margin.top]);

const xAxis = g => g
  .attr('transform', `translate(0, ${height - margin.bottom})`)
  .call(d3.axisBottom(x)
    .tickSizeOuter(0))
  .call(g => g.select('.domain').remove())
  .call(g => g.selectAll('line').remove());

const yAxis = g => g
  .attr('transform', `translate(${margin.left}, 0)`)
  .call(d3.axisLeft(y))
  .call(g => g.select('.domain').remove())
  .call(g => g.selectAll('line')
    .attr('x2', width)
    .style('stroke', '#f5f5f5'))


const svg = d3.select('#svg-area').append('svg').style('width', width).style('height', height);

const handleClickRect = (d, i) => {
  svg.selectAll('rect').each(function(d, j) {
    if(j === i) d3.select(this).style('fill', pointColor);
    else d3.select(this).style('fill', baseColor);
  });
};

svg.append('g').call(xAxis);
svg.append('g').call(yAxis);
svg.append('g')
  .selectAll('rect').data(data).enter().append('rect')
  .attr('x', d => x(d.name))
  .attr('y', d => y(d.value))
  .attr('height', d => y(0) - y(d.value))
  .attr("rx", 15)
  .attr('width', x.bandwidth())
  .attr('fill', baseColor)
  .attr('data-x', d => d.name)
  .attr('data-y', d => d.value)
  .on("click", handleClickRect);

svg.node();
handleClickRect(null, data.length - 1);