Changing the background color of the legend text when hovering over a d3 doughnut chart

I have a doughnut chart that displays values on mouse hover. However, I would like to change the background of the legend text when hovering over the respective area of the doughnut chart.

return {
    restrict: 'E',
    scope: {
        values: '='
    },
    link: function (scope, element, attrs) {
        scope.$watch('values', function(values) {
            var data = [];
            if(values) { 
                console.log('values from directive: ', values); 

              var w = 700,
                h = 700,
                r = 290,
                inner = 190,
                color = d3.scale.category20();

          data=values;
            var total = d3.sum(data, function(d) {
                return d3.sum(d3.values(d));
            });
            var vis = d3.select("#pieChartsD3")
                .append("svg:svg")
                .data([data])
                .attr("width", w)
                .attr("height", h)
                .append("svg:g")
                .attr("transform", "translate(" +320+ "," +320+ ")")
            var textTop = vis.append("text")
                .attr("dy", ".35em")
                .style("text-anchor", "middle")
                .attr("class", "textTop")
                .text( "TOTAL" )
                .attr("y", -10),
            textBottom = vis.append("text")
                .attr("dy", ".35em")
                .style("text-anchor", "middle")
                .attr("class", "textBottom")
                .text(total.toFixed(0) )
                .attr("y", 10);
            var arc = d3.svg.arc()
                .innerRadius(inner)
                .outerRadius(r);
            var arcOver = d3.svg.arc()
                .innerRadius(inner + 20)
                .outerRadius(r + 20);

            var pie = d3.layout.pie()
                .value(function(d) { return d.val; });

            var arcs = vis.selectAll("g.slice")
                .data(pie)
                .enter()
                    .append("svg:g")
                        .attr("class", "slice")
                         .style('word-wrap', 'break-word')
                        .on("mouseover", function(d) {
                            d3.select(this).select("path").transition()
                                .duration(200)
                                .attr("d", arcOver)

                            textTop.text(d3.select(this).datum().data.name)
                                .style('fill', 'red')

                                .attr("y", -10);
                            textBottom.text(d3.select(this).datum().data.val.toFixed(0))
                                .style('fill', 'blue')
                                .attr("y", 10);
                        })
                        .on("mouseout", function(d) {
                            d3.select(this).select("path").transition()
                                .duration(100)
                                .attr("d", arc);

                            textTop.text( "TOTAL" )
                                .attr("y", -10);
                            textBottom.text(total.toFixed(0));
                        });
            arcs.append("svg:path")
                .attr("fill", function(d, i) { return color(i); } )
                .attr("d", arc);
            console.log("datas length: "+data.length)
            var legend = d3.select("#legend").append("svg")
                .attr("class", "legend")
                .attr("width", 400)
                .attr("height", 20*data.length)
                .selectAll("g")
                .data(data)
                .enter().append("g")
                .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
            legend.append("rect")
                .attr("width", 18)
                .attr("height", 18)
                .style("fill", function(d, i) { return color(i); });
            legend.append("text")
                .attr("x", 24)
                .attr("y", 9)
                .attr("dy", ".35em")
                .text(function(d) { return d.name; });


        }

    })
}
}

https://i.stack.imgur.com/Id7kM.png

Answer №1

(Just a heads up, I'm making an educated guess about the content of your request since you didn't provide a specific question. Here's what I suggest...)

Within the .on("mouseover", function(d) { section, include the following code snippet:

legend.filter(function(l){
  return l === d; // where d represents the data bound to the donut segment
})
.attr("fill","yellow")

Remember to add the logic to revert this change by setting fill back to grey or none in the .on("mouseout" event handler.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a vertical scrollable content using FlexBox

Struggling to create a scrollable box using flex The Box element with the id=scroll is not behaving as expected, causing content overflow How do I set the Box to overflow=auto and enable scrolling for the content? Spending countless hours trying to unrav ...

Setting the image source for each image in a table using VB.net

Is it more efficient to loop through the img src of various cells using a For Each loop and set their src based on another value (x) by directly referencing the img src attributes in code, or would embedding the table in a control higher up the hierarchy ...

Should you include the dollar sign in a Vue HTML variable or not?

I’m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Styling Tip: Aligning text to the baseline of a height-adjusted input field using CSS

As per the information from the Mozilla documentation, it states that I can align the text in an input field to the baseline if the element's display property is set to inline-block. I have made adjustments to the height of several input elements, bu ...

Sending input values to controller action parameters in CakePHP

I am working on an HTML form in which I need the URL output to be structured as follows: "example.com/mycontroller/action/mike/apple" Upon submitting the form using "post" method, the form values are not visible and can only be accessed through "_POST" ...

406 error is triggered by GET parameters

Here is a PHP script I have: <!DOCTYPE html> <html lang="es-ES" xmlns="http://www.w3.org/1999/xhtml" xml:lang="es-ES"> <head> <meta charset="iso-8859-1" /> </head> <body><p><?php if(isset($_GET['echo& ...

Causing an element to extend beyond its parent element's boundaries

I have implemented Material Design Lite for creating cards on my website. I encountered an issue where the menu I added to the card only displays within the bounds of the card. I would like it to overflow similar to this example () Here is a link to my fi ...

Increase the padding for each child element within its corresponding parent

Is it possible to add padding to child items within each "folder" element without using JavaScript if there is more than one? This scenario would be hardcoded as follows: folder folder inner { padding-left: 14px; } folder folder folder inner { pad ...

Ways to eliminate the up and down arrow in the MUI number field

How can I remove the up and down arrow from the MUI number field? My current version is 5.3.0. Is it possible to achieve this using the sx prop? Learn more about the sx prop here <TextField sx={{...}} id="outlined-number" label="Nu ...

The latest Chrome update has caused a decrease in rendering and loading speeds for Ajax and Angular network

It has been around two weeks since a Chrome update caused trouble for users of my angular app. Previously, the entire single page application loaded in under 4 seconds, but after the update, every user was experiencing load times exceeding 40 seconds. Surp ...

Discovering if an email is already registered using AngularJS and Spring Boot

After some careful consideration, I believe I am close to resolving my issue but I still require a little bit of fine-tuning. Within my @RestController, I have implemented the following code snippet to verify the existence of a user: @RequestMapping(valu ...

Identifying when floats exceed their limits

Is there a way to identify overflow on floating elements? It's important to note the difference between setting overflow to visible or hidden. overflow: visible; overflow: hidden; Do all floated elements inherently contain overflow? Why is it chal ...

Linking the value of an expression to ngModel

There is a specific scenario where I need the ng-model property to bind to a value retrieved from the database as part of the business logic. To illustrate this concept, I have set up an example function TodoCtrl($scope) { $scope.field1 = "PropertyFr ...

Is there a way to set the starting position of the overflow scroll to the middle?

Is there a way to have the overflow-x scrollbar scroll position start in the middle rather than on the left side? Currently, it always begins at the left side. Here is what it looks like now: https://i.stack.imgur.com/NN5Ty.png If anyone knows of a soluti ...

Utilizing Typescript for directive implementation with isolated scope function bindings

I am currently developing a web application using AngularJS and TypeScript for the first time. The challenge I am facing involves a directive that is supposed to trigger a function passed through its isolate scope. In my application, I have a controller r ...

Searching for text within an HTML document using Selenium in Python can be easily achieved by using the appropriate methods and

Is there a way to find and retrieve specific texts within an HTML file using Selenium in Python, especially if the text is not enclosed within an element? <div class="datagrid row"> ==$0 <h2 class="bottom-border block">Accepted Shipment</h ...

Various instances of controllers in Angular.js and JavaScript

I'm facing a challenge with a view that has two identical parts but different content. I want to find a way to use one controller and one view for both the left and right parts. Here's what I currently have in my HTML: <div class="board_bod ...

CanJS utilizes mustache templates to escape HTML tags

I have a requirement to present a series of choices to the user. I am using a mustache template along with the CanJS JavaScript framework to showcase these options. The problem arises when attempting to display an option such as: Potato Rs. 12 The mustac ...

Disabling cache in AngularJS is being overridden by Chrome's cache

I'm currently encountering an interesting caching issue while using Chrome. My angularjs service looks like this: var url = '/api/acts/' + accountId + '/policy/?filter=NEW_POLICY'; return $http({ ...

What is the procedure for eliminating an event listener that does not directly invoke a function?

I have implemented an event listener in my JS file following a successful AJAX request: var pageButtonsParentElement = document.getElementById("page-buttons"); pageButtonsParentElement.addEventListener('click', event => { ...