Home > Blockchain >  Underline node text on mouse over
Underline node text on mouse over

Time:09-18

I have a graph made with d3.js and I have the following attributes and properties for the nodes:

 // Enter any new nodes at the parent's previous position
  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "rotate("   (d.x - 90)   ")translate("   d.y   ")"; })
      .on("click", click)
      .on("dblclick", dblclick)

I would like to add the ability to underline the node title when hovering over it. Something like this which unfortunately doesn't work:

  var nodeEnter = node.enter().append("g")
      .on("mouseover").style("text-decoration","underline")
      .on("mouseout").style("text-decoration","none")

EDIT: I would prefer to put a condition to make this happen only for some nodes of the graph.

CodePudding user response:

You aren't using the selection.on() method correctly. In order to do something on an event you need to provide the method with a second parameter: a function that describes the action taken on the event:

D3v6

.on("mouseover", function(event, datum) { ... })

D3v5 and before

.on("mouseover", function(datum, index, nodes) { ... })

In all versions of D3 this will be the target element (unless using arrow notation). The datum is the data bound to the target element, one item in the array passed to selection.data().

If you only provide one parameter it returns the current event handling function assigned to that event. In your case you likely haven't done this already (because you are attempting to do so), so .on("mouseover").style(...) will return an error such as "Cannot find property style of null" because .on("mouseover") will return null: there is no event handling function assigned to this event to return.

So, to highlight nodes on mouseover with some logic so we can have different outcomes for different nodes, we can use something like:

 selection.on("mouseover", function(event, datum) {
   if(datum.property == "someValue") {
      d3.select(this).style("text-decoration","underline");
   }
 })
 .on("mouseout", function(event,datum) {
    d3.select(this).style("text-decoration","none");
 })

Where the if statement can be replaced with whatever logic you prefer.

I see you are probably using a hierarchical layout generator, D3's hierarchical layout generators nest the original datum's properties into a data property so that layout properties and non layout properties do not collide, so datum.property may reside at datum.data.property (log the datum if you are having trouble).

CodePudding user response:

You can add an underline on hover using CSS

.node:hover{
    text-decoration: underline;
}
  • Related