Ask Your Question
2

How to set the stroke attribute of a rectangle element when the mouse is over it in D3?

asked 2023-02-14 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-10 22:00:00 +0000

plato gravatar image

To set the stroke attribute of a rectangle element when the mouse is over it in D3, you can use the mouseover and mouseout events. Here is an example code snippet:

// Select the rectangle element var rect = d3.select("rect"); // Define the stroke width, color, and hover color var strokeWidth = 2; var color = "black"; var hoverColor = "red"; // Set the initial stroke attribute rect.attr("stroke", color) .attr("stroke-width", strokeWidth); // Add mouseover event listener rect.on("mouseover", function() { // Change the stroke attribute to the hover color d3.select(this).attr("stroke", hoverColor); }) // Add mouseout event listener .on("mouseout", function() { // Change the stroke attribute back to the original color d3.select(this).attr("stroke", color); }); 

In this code, we first select the rectangle element using the d3.select() method. We then define the stroke width, color, and hover color as variables.

We set the initial stroke attribute of the rectangle using the .attr() method. We then add a mouseover event listener using the .on() method. When the mouse is over the rectangle, the function changes the stroke attribute to the hover color using the d3.select().attr() method.

We also add a mouseout event listener to change the stroke attribute back to the original color when the mouse leaves the rectangle.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-14 11:00:00 +0000

Seen: 11 times

Last updated: Mar 10 '22