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

Submenu in submenu not registering CSS hover events

Currently, on a website project that I'm developing, there is a submenu nested within another submenu. Interestingly enough, the level-2 submenu happens to be taller than its parent level-1 submenu. To control the visibility of these submenus, I' ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

Prevent the utilization of <span> tags for line breaks to

When resizing my window to a smaller size, I encountered some unsightly spans that cut into new lines. To demonstrate this issue, I intentionally set the width:20px;. Can this problem be avoided? <link href="https://maxcdn.bootstrapcdn.com/bootstrap/ ...

When using Angular to send a DELETE request to a Django-Rest API, it may be mistakenly interpreted

Attempting to consume a REST API created with Django-Rest using AngularJS, but encountering an issue. When sending a DELETE request, the Django-Rest sees OPTIONS instead. This is what has been done: In my Django views.py @api_view(['GET', &apo ...

Interactive jQuery Dropdown Menu with Multiple Divs

I have been working on this and I'm almost there, but the jQuery part is driving me crazy (I'm not very proficient in it yet, but I am learning). Here's the link to the fiddle: http://jsfiddle.net/5CRA5/4/ Since I can't demonstrate th ...

Alignment issues with images

I am trying to put together a collection of images that function as links and light up when hovered over. However, my attempt to add a <div class="hover"> in front of each image caused them to no longer display in a horizontal line. How can I resolve ...

Dynamic scaling and positioning of multiple images in relation to each other using CSS

I am currently working on layering images over a large logo and making sure it remains responsive. I want the overlaid images to maintain their position on the logo even when the browser window size is reduced. Here is what my current browser display look ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...

What is the best way to ensure that the same information is included on every page of

Currently developing a dynamic website where certain components such as the fixed header, menubar, and footer are common across multiple pages. What is the best way to include these fixed components on every webpage? I am utilizing JSP and JavaScript for ...

Is it possible to track the movement of two phones within a specific location?

I'm currently working on a mobile app using Ionic that requires the backend or another user to be able to detect the movement of a different user. Here's how it would work: I need to mark a location with specific coordinates and save them. Onc ...

Creating a multiline centered navigation bar item using Bootstrap 4

My navigation bar is functioning properly with single-line items, but encounters alignment issues when dealing with multi-line items: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

What causes the appearance of a slight space between a child element positioned absolutely and its parent element with borders? All the margins, padding, and positions have been assigned a value of

I have encountered a peculiar issue that I managed to recreate in a simplified version. In my scenario, the parent element has the CSS property position: relative, while the child element with the ::after pseudo-element has position: absolute and all direc ...

How can I add text to the title of a border using Bootstrap5?

I am attempting to create a design where text appears within the border of an element. I am currently utilizing Bootstrap 5 and jQuery for this project. Despite my efforts with fieldset and legend elements, I have not been successful in achieving the desir ...

Employing JavaScript for fading divs in and out sequentially

Hey there! I'm currently struggling with implementing transitions for my tool tips. Any assistance would be greatly appreciated! I am looking to have my "fader" divs fade in and out on click of a button, with each transition lasting 5 seconds. It&apo ...

How to retrieve the chosen row in an angularjs UI-GRID when the row selection event occurs

Within my application, I am utilizing a ui-grid and I am aiming to retrieve the selected row when a user chooses a row from the grid (where only one row can be selected at a time). I have successfully been able to obtain the selected rows through gridApi ...

How can I retrieve the current background color and revert it back after a .hover event?

I am trying to use the .hover function to change the background color of a menu. Each menu item has a different background color, so I want it to return to its original color when the user hovers off. In other words, I want the script to read the current b ...

Updating the fixed value and sending it to subordinate controllers in Angular version 1.4.9

I'm facing an issue with updating the value of a constant from the root controller. When the state transitions to a login controller, the constant still holds the old value. The CONSTANT is initially defined like this: var myApp = angular.module("ap ...

Tips for aligning a div underneath another div in a centered position

I am attempting to align .rij_lessenrooster below .rij_weekdagen so that it is centered under each day. The teacher advised me to create a column and then try it, but it did not resolve the alignment issue. The .rij_weekdagen consistently appears off to th ...