I have used d3.js to draw some circles on an SVG container.
I have successfully set the mouseover behavior on these circles to print simple console messages. I see those console messages when I mouseover (and mouseout) so I know they are working properly.
However, instead of printing that console messages, I want to change the cursor to the hand when I mouseover them, and I want to change the cursor back to the normal arrow when I mouse out. Given my code below, how can I do it?
On mouseover, I know I need to change the style property cursor
to pointer
and on mouseout, I know I need to change it to default
but I don't know the syntax of how I should do it. Can someone please explain it to me? Below is my code.
var myCircle = svgContainer.selectAll(".dots")
.data(myDataList).enter().append("circle")
.attr("class", "dots")
.attr("cx", function(d, i) {return d.centerX})
.attr("cy", function(d, i) {return d.centerY})
.attr("r", 5)
.attr("stroke-width", 0)
.attr("fill", function(d, i) {return "red"})
.style("display", "block");
myCircle.on({
"mouseover": function(d) {
console.log('Hello World!'); // What do I change this to?
},
"mouseout": function(d) {
console.log('Goodbye World!'); // What do I change this to?
}
}
);
You can simply use the CSS cursor property with the value pointer to change the cursor into a hand pointer while hover over any element and not just hyperlink. In the following example when you place the cursor over the list item, it will change into a hand pointer instead of the default text selection cursor.
There are two possible methods of creating tooltips in D3. js. The first method is by creating the SVG <title> tags as a descendant of an interactable element. The second approach is to use mouseover , mosueleave , and mousemove events to dynamically move and change the visibility of a tooltip.
You can do it like this:
myCircle.on({
"mouseover": function(d) {
d3.select(this).style("cursor", "pointer");
},
"mouseout": function(d) {
d3.select(this).style("cursor", "default");
}
});
working code here
OR
you can simply work this out in the CSS.
myCircle.style('cursor', 'pointer')
Why don't you simply let CSS handle it?
.dots {
cursor: pointer;
}
Did you just try this :
var myCircle = svgContainer.selectAll(".dots")
.data(myDataList).enter().append("circle")
.attr("class", "dots")
.attr("cx", function(d, i) {return d.centerX})
.attr("cy", function(d, i) {return d.centerY})
.attr("r", 5)
.attr("stroke-width", 0)
.attr("fill", function(d, i) {return "red"})
.style("display", "block")
.style("cursor", "pointer");
Because when you define cursor as a pointer for your object, when you "mouseover", then the pointer become a pointer.
See here an example : https://jsfiddle.net/oj5vubxn/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With