Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 js know if an svg shape has a class

I want to have a toggle button in an svg shape, and scale it down when the button is clicked, then scale up when clicked again, firstly I added a class collapse like this. I want to remove the class if it has a class collapse

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(hasClass("collapse")) # HOW DO I DO THIS
    )
like image 852
Joey Hipolito Avatar asked Dec 11 '22 09:12

Joey Hipolito


1 Answers

You can do this with the DOM API:

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(this.classList.contains("collapse")) {
        // ...
        // this.classList.remove('collapse')
      } else {
        // ...
        // this.classList.add('collapse')
      }
    )    

Or jQuery:

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if($(this).hasClass("collapse")) {
        // ...
      }
    )

The this inside the call backs refers to the DOM Element. This is, however, not quite the D3-isque way of doing things. One should save the collapsed status on the data associated with the node and act on it rather than save the status in the class of the DOM elements.

like image 65
musically_ut Avatar answered Dec 28 '22 17:12

musically_ut