d3 on (2)

d3 on (2)

by Shang-De You

JavaScript

var svg = d3.select("body").append("svg")
	.attr("width", 500)
  .attr("height", 500)
  
var rect = svg.append("rect")
	.attr("fill", "steelblue")
  .attr("width", 50)
  .attr("height", 50)
  .attr("x", 100)
  .attr("y", 100)
  
rect.on("click", function(){
	console.log(d3.mouse(this))
})

var text = svg.append("text")
	.attr("display", "none")

rect
  .on("mousemove", function(){
    var x = d3.mouse(this)[0]
    var y = d3.mouse(this)[1]

    text.attr("display", null)
      .attr("x", x + 20)
      .attr("y", y)
      .text("[" + x + "," + y + "]")
  })
	.on("mouseout", function(){
  	text.attr("display", "none")
  })