Tips for customizing the appearance of a tooltip in an NVD3 Chart

Exploring the NVD3 framework and attempting to enhance a customized tooltip for a specific pie chart given below:

var app = angular.module('plunker', ['nvd3']);

app.controller('MainCtrl', function($scope) {
  $scope.options = {
        chart: {
            type: 'pieChart',
            height: 500,
            x: function(d){return d.key;},
            y: function(d){return d.y;},
            color:['#CE1B1F', '#FFC455', '#00A6CD'],
            showLabels: false,
            duration: 500,
            labelThreshold: 0.01,
            labelSunbeamLayout: true,
            legend: {
                margin: {
                    top: 5,
                    right: 35,
                    bottom: 5,
                    left: 0
                }
            }
        }
    };

    $scope.data = [
        {
            key: "A",
            y: 2
        },
        {
            key: "B",
            y: 1
        },
        {
            key: "C",
            y: 3
        },
    ];
});

Considering methods to personalize the tooltip to match a desired style, based on Krispo's sample on [github][1]. Any suggestions on how to achieve this?

Answer №1

To implement a custom tool-tip feature, you must include the tooltip in the existing nvd3 options as shown below:

tooltip: {
     contentGenerator: function (e) {
           //Create and return customized tool-tip as HTML using e.series and e.data
     }
}

If you require additional values or attributes for each series, you can define them within $scope.data like this:

$scope.data = [
        {
            key: "CAT I",
            y: 2,
            MyAttribute1:"DLA Avn ... CAT I",
            MyAttribute2:"DLA Energy ... CAT I"
        },
        {
            key: "CAT II",
            y: 3,
            MyAttribute1:"DLA Avn ... CAT II",
            MyAttribute2:"DLA Energy ... CAT II"
        },
        {
            key: "CAT III",
            y: 1,
            MyAttribute1:"DLA Avn ... CAT III",
            MyAttribute2:"DLA Energy ... CAT III"
        },
    ];

Now, you can access these custom values within the tool-tip function using e.data like so:

tooltip: {
         contentGenerator: function (e) {
              var series = e.series[0];
              if (series.value === null) return;

              var rows = 
                "<tr>" +
                  "<td class='key'>" + series.key + '- #3: ' + "</td>" +
                  "<td class='x-value'>" + e.data.MyAttribute1 + "</td>" + 
                "</tr>" +
                "<tr>" +
                  "<td class='key'>" + series.key + '- #5: ' + "</td>" +
                  "<td class='x-value'>" + e.data.MyAttribute2 + "</td>" + 
                "</tr>";

              var header = 
                "<thead>" + 
                  "<tr>" +
                    "<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
                    "<td class='key'><strong>" + series.key + "</strong></td>" +
                  "</tr>" + 
                "</thead>";

              return "<table>" +
                  header +
                  "<tbody>" + 
                    rows + 
                  "</tbody>" +
                "</table>";
            } 
}

You can view an updated version on this Edited Plunker to see how it is implemented.

I hope this explanation clarifies any doubts.

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

Develop a JavaScript function

Is there a way to define the properties of an object in HTML and then create a function in JavaScript that will return that object? This is the HTML code: <object id="desktop" type="application/x-desktop" width="500" height="200> <param name="cl ...

Extract information from non-JSON formatted response

Here is the fetch request that I am working with: fetch('https://cdnjs.cloudflare.com/ajax/libs/jsbeautify/1.7.5/beautify.js') .then(function (result) { console.log('here is our content:', result.body); }) .ca ...

Is there a way to display only the first 5 divs and then include a "Load more" button to view the rest

I've got the code below and everything is working fine. However, when I add that script code into my project, it doesn't work. There are no errors in the console. Why is this happening? In Fiddle, everything runs smoothly. Could it be due to usin ...

Unexpected behavior of Ajax response from PHP

When I click the button, I am calling the JavaScript function cancelAppointment. I can see that the function is running properly because the first alert is displayed. I have tried following various guides to make this work, but so far I have not had any s ...

Implement jQuery autocomplete on duplicated element

My implementation of jQuery autocomplete is functioning well with existing elements but not with dynamically added elements. This is the modified autocomplete code I am using: $(function() { (function( $ ) { $.widget( "ui.combobox", { ...

The click event fails to trigger on dynamically loaded Ajax content

I've encountered an issue while loading content using ajax from external HTML Files. After the content is loaded, the click event doesn't seem to be working in Safari (including mobile safari) for any of the newly loaded elements such as ul, li, ...

What is the formula for calculating the y-axis rotation based on a 2D direction vector?

I'm currently developing a 3D game and I am facing a challenge with ensuring that the player mesh is always oriented towards the back of the camera. Although I have successfully obtained a 2D speed vector representing the direction along the x-z plane ...

Error encountered while attempting to execute uBlock Origin core in NodeJS: "snfe.useLists function not found"

Having completed the installation of the ubo-core package (npm install @gorhill/ubo-core) and including it in my project, I am encountering an issue with using the StaticNetFilteringEngine instance. This is my code snippet (ublock.mjs): async function rea ...

Response Headers in Google Cloud Functions

When executing a GCF triggered by an Http Request, I encounter the issue of receiving unnecessary headers along with my custom message. Here is a list of headers that are included: HTTP/1.1 200 OK Server: nginx Content-Type: application/json; charset=utf- ...

Having trouble retrieving a specific item from my AngularJS resource because it is not indexed properly

In my current setup, the controller looks like this: .controller( 'AppCtrl', function AppCtrl ( $scope, $location, $resource ) { var Card = $resource('http://localhost/card/:cardId', { 'cardId': "@_id" ...

Issue encountered in performing a post request using AngularJS

One of the functions in my code is a post call: save2 : function ( lotto ) { var configDistintaIngrediente = { params: { distintaBaseGelato_id: 1, ingrediente_id: 2, quantit ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

Is there a way to leverage the useSWR hook for making numerous requests simultaneously?

I am attempting to utilize the useSWR hook for multiple calls, but I keep encountering an error message that reads: Cannot read properties of null (reading 'destroy') async function FetchApi(url) { const response = await fetch(url); const ...

Issues involving adding elements to an array in CSS, JS, and HTML

I am currently working on a module where exam information is stored in an array and passed to another JavaScript file using localStorage. However, I'm facing an issue where the previous exam data keeps getting overwritten despite using .push method. A ...

Unable to define the 'grid' property as it is currently undefined

Recently started working with Angular and ng-grid, encountering an issue while trying to display a simple static json file in the grid. The error message shown is: Cannot set property 'grid' of undefined Seeking assistance from experts out t ...

A guide on activating dropdown buttons individually using AngularJS (Cascading dropdowns)

When it comes to cascading dropdowns (for example: with 3 dropdowns), the challenge is to disable the 2nd and 3rd dropdown initially. Only when a user selects an option in the 1st dropdown, should the 2nd dropdown be enabled. Similarly, once an option is s ...

Display div content depending on the clicked ID in AngularJS

Unique Header Links HTML <ul ng-controller="pageRouteCtrl"> <li ui-sref-active="active"> <a ui-sref="home" class="" ng-click="getPageId('live-view')">LIVE</a> </li> <li> <a ng-clic ...

Capture a section of the body background to incorporate into the canvas space

As a newcomer to the world of canvas, I have been learning from various sources about how it works. However, my goal is more dynamic and unique than what I've seen so far. I am looking to create a body background for my webpage that is responsive, cen ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...