Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can it is possible to use click event in tag cloud of D3 and If yes how?

Tags:

d3.js

d3-cloud About click event Can it is possible to use click event in tag cloud of D3 and If yes how

<!DOCTYPE html>
<meta charset="utf-8">
<script src="../lib/d3/d3.js"></script>
<script src="../d3.layout.cloud.js"></script>
<body>
<script>
  var fill = d3.scale.category20();
  var zz= ["Hello", "world", "normally", "you", "want", "more", "words", "than", "this"];
  d3.layout.cloud().size([300, 300])

      .words((zz).map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      }))
      .rotate(function() { return ~~(Math.random() * 2) * 90; })
      .font("Impact")
      .fontSize(function(d) { return d.size; })
      .on("end", draw)
      .start();

  function draw(words) {
    d3.select("body").append("svg")
        .attr("width", 300)
        .attr("height", 300)
      .append("g")
        .attr("transform", "translate(150,150)")
      .selectAll("text")
        .data(words)
      .enter().append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return fill(i); })
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; });
  }
</script>

( I want "Hello", "world", "normally", "you", "want", "more", "words", "than", "this" words to be clickable)

like image 395
Nilesh1021 Avatar asked Jan 17 '13 09:01

Nilesh1021


2 Answers

you can bind events with .on

I will show you how to enlarge or reduce the tag size when mouse hovering, and to log when clicking a tag (i'm using coffee script)

.on("mouseover", ->
  d3.select(this).style("font-size", (d) ->
    d.size + 10 +"px"
  )
.on("mouseout", ->
  d3.select(this).style("font-size", (d) ->
    d.size - 10 +"px"
  )
.on("mousedown",  ->
  console.log(this)
like image 23
Luchux Avatar answered Oct 28 '22 07:10

Luchux


Just add the following at the end of your script:

...
.text(function(d) { return d.text; })
.on("click", function(d) {
    alert(d.text);
  });
like image 198
PhoebeB Avatar answered Oct 28 '22 08:10

PhoebeB