Ways to show text on a donut chart when hovering with the mouse

I have been attempting to make adjustments to this sample. My goal is to display a word in the center of the donut chart upon mouseover, similar to this:

https://i.sstatic.net/dCPKP.png

Although I have included code for mouseover, it seems to not be functioning properly.

Code

const eventObj = {
          'mouseover': function (d, i, j) {
              pathAnim(d3.select(this).select('path'), 1);
              centerTxt.text(function () {
                  return d.data.label;
              })
              // .call(wrap, 40);
          },
          'mouseout': function (d, i, j) {
              const thisPath = d3.select(this).select('path');
              if (!thisPath.classed('clicked')) {
                  pathAnim(thisPath, 0);
              }
              centerTxt.text(function (d) {
                  return '';
              });
          },


                'click': function(d, i, j) {


                    var thisPath = d3.select(this);
                    var clicked = thisPath.classed('clicked');
                    pathAnim(thisPath, ~~(!clicked));
                    thisPath.classed('clicked', !clicked);

                    //setCenterText(thisDonut);
                }
            };

            var pathAnim = function(path, dir) {
            switch(dir) {
                case 0:
                    path.transition()
                        .duration(500)
                        .ease('bounce')
                        .attr('d', d3.svg.arc()
                            .innerRadius((radius-100))
                            .outerRadius(radius-50)
                        );
                    break;

                case 1:
                    path.transition()
                        .attr('d', d3.svg.arc()
                            .innerRadius((radius-100))
                            .outerRadius((radius-50) * 1.08)
                        );
                    break;
            }
        }  

Answer №1

Below is the solution you are seeking:

var data = [{
    label: 'Star Wars',
    instances: 207
}, {
    label: 'Lost In Space',
    instances: 3
}, {
    label: 'the Boston Pops',
    instances: 20
}, {
    label: 'Indiana Jones',
    instances: 150
}, {
    label: 'Harry Potter',
    instances: 75
}, {
    label: 'Jaws',
    instances: 5
}, {
    label: 'Lincoln',
    instances: 1
}];

svg = d3.select("svg");
canvas = d3.select("#canvas");
art = d3.select("#art");
labels = d3.select("#labels");

canvas.append("circle")
    .attr('cx', 0)
    .attr('cy', 0)
    .attr('fill', 'pink')
    .attr('r', 48);
canvas.append("text")
    .attr("text-anchor", "middle")
    .attr('font-size', '12px')
    .attr('y', 0)
    .attr('id', 'center-text')
    .text('TEST FOR A LONG VERY TEXT');

// Wrap text in a rectangle.
d3plus.textwrap()
    .container(d3.select("#center-text"))
    .resize(true)
    .draw();

jhw_pie = d3.layout.pie()
jhw_pie.value(function(d, i) {
    return d.instances;
});

cDim = {
    height: 500,
    width: 500,
    innerRadius: 50,
    outerRadius: 150,
    labelRadius: 175
}

svg.attr({
    height: cDim.height,
    width: cDim.width
});

canvas.attr("transform", "translate(" + (cDim.width / 2) + "," + (cDim.width / 2) + ")");

pied_data = jhw_pie(data);

pied_arc = d3.svg.arc()
    .innerRadius(50)
    .outerRadius(150);


const eventObj = {
    mouseover: function(d, i, j) {
        d3.select('#center-text').text(d.data.label);
        d3plus.textwrap()
            .container(d3.select("#center-text"))
            .resize(true)
            .draw();
    },
    mouseout: function(d, i, j) {
        d3.select('#center-text').text('');
        d3plus.textwrap()
            .container(d3.select("#center-text"))
            .resize(true)
            .draw();
    },


    click: function(d, i, j) {

    }
};

enteringArcs = art.selectAll(".wedge").data(pied_data).enter();

enteringArcs.append("path")
    .attr("class", "wedge")
    .attr("d", pied_arc)
    .on('click', (d) => {
        eventObj.click(d)
    })
    .on('mouseover', (d) => {
        eventObj.mouseover(d)
    })
    .on('mouseout', (d) => {
        eventObj.mouseout(d)
    })
    .style("fill", function(d, i) {
        return color(i);
    });

enteringLabels = labels.selectAll(".label").data(pied_data).enter();
labelGroups = enteringLabels.append("g").attr("class", "label");

textLines = labelGroups.append("line").attr({...});
textLabels = labelGroups.append("text").attr({...}).text(function(d) {...});

alpha = 0.5;
spacing = 12;

function relax() {
    // Function code here
}

relax();
.label-text {
    alignment-baseline: middle;
    font-size: 12px;
    font-family: arial,helvetica,"sans-serif";
    fill: #393939;
}
.label-line {
    stroke-width: 1;
    stroke: #393939;
}
.label-circle {
    fill: #393939;
}
<svg>
    <g id="canvas">
    <g id="art" />
    <g id="labels" /></g>
</svg>

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

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

What is the best way to modify a state in nextjs?

Recently, I've been working on a next.js project that includes a shopping cart feature. Essentially, when you click on an item, its image is added to a list and displayed with all the other selected items. To remove an item, users can simply click on ...

Using Node.js, Socket.IO, and Express to deliver static JavaScript files served dynamically

I have been working on a node.js application that utilizes socket.io and express. Initially, all of the javascript was included in the HTML file, but now I am looking to separate it into a .js file. In my primary node application, this is what I currently ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

Tips on creating an onclick function in javaScript and linking it to innerHTML

let a = 10; let b = 15; document.getElementById("text").innerHTML = '<div onclick=\'testing("'a + '","' + b + '") > text </div>'; Welcome, I am new to this ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...

Retrieve error message from 400 error in AngularJS and WebAPI

Why am I having trouble reading the error message in AngularJS from this code snippet? ModelState.AddModelError("field", "error"); return BadRequest(ModelState); Alternatively, return BadRequest("error message"); return Content(System.Net.HttpStatusCod ...

Error 504 'FUNCTION_INVOCATION_TIMEOUT' encountered on NextJS/Vercel deployment

Encountering an error on one of my pages after deploying to vercel, everything functions properly in dev mode. I suspect the issue lies with one of my fetch/APIs as it utilizes the data from the initial fetch request as the URL for the subsequent fetch re ...

Issue with the DocPad plugin for Gulp

I'm encountering an issue while trying to utilize the gulp docpad plugin. When I run docpad run, the following error message is displayed: Error: spawn UNKNOWN at exports._errnoException (util.js:837:11) at ChildProcess.spawn (internal/child_process. ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

Angular Typescript filter function returning an empty arrayIn an Angular project, a

I have a filtering function in Angular that is returning an empty array. Despite trying similar solutions from previous questions, the issue persists. The function itself appears to be correct. Any assistance would be greatly appreciated. gifts represents ...

Adding JSON data to an array for Flot Diagram

I've been struggling with the task of organizing data into an array. The existing temp array is structured as follows: tmp[0][0] = "NY" tmp[0][1] = "52" tmp[1][0] = "FL" tmp[1][1] = "25" My goal is to transfer this data into a new array called data. ...

Having trouble with the chaining of AJAX calls using Promises?

I am currently attempting to send a POST request (technically a DELETE) to a php page called delete_post.ajax.php. This request takes data from my AJAX call and utilizes it to delete an item from the database. After deletion, I want my AJAX to then send a ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...