Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign unique id to SVG text element in d3 javascript

Making a bar graph in d3. I have 30+ bars, with 30+ corresponding labels on x-axis. I would like x-axis labels to be hidden when the page loads (this is working), AND APPEAR only if user cursors over the corresponding bar (svg rect object). To do this I am assigning an id to each rect and each text element. When user cursors over rect, text will appear for ONLY the selected (mouseover'd) rect.

I can assign id to rects, but not for text. Code:

      svg.selectAll("rect")
         .data(dataset)
         .enter()
         .append("rect")
            .attr("id", function(d){   
                return d.slug;        // slug = label downcased, this works
            });                       // each rect has unique id

However, similar code for my text element on x-axis doesn't assign an id?!

    svg.append("g")
      .call(xAxis)
      .selectAll("text")
        .attr("id", function (d){    // inspect text element shows no ID.
           return d.slug;            // text doesn't have any id
        })
     .style("text-anchor", "end")
     .attr("opacity", 0.2);

How can I assign a unique id to my text elements in x-axis? Thank you!

like image 957
DeBraid Avatar asked Oct 15 '13 17:10

DeBraid


1 Answers

The problem is that no data is bound to the x axis ticks and therefore d is undefined -- you should actually get an error message when running your code.

In this particular case, you can use the index to get the relevant data item like so.

svg.append("g").call(xAxis)
   .selectAll("text")
   .attr("id", function(d, i) { return dataset[i].slug; });

Note that this will only work if the number of axis ticks is the same as the number of data items.

like image 118
Lars Kotthoff Avatar answered Oct 30 '22 11:10

Lars Kotthoff