Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.