Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, the tooltip isn't appearing as expected. If anyone could shed light on what I might be overlooking or where I may have gone astray, it would be greatly appreciated.

Many thanks in advance!

                    bar.enter()
                        .append("g")
                        .attr("class", "bar-container")
                        .append("rect")
                        .attr("class", "bar")
                        .attr('fill','#4EC7BD')
                        .attr("x", function(d) { return x(d.id); })
                        .attr("y", function(d) { return y(eval('d.'+scope.metric)); })
                        .attr("height", function(d) { return height - y(eval('d.'+scope.metric)); })
                        .attr("width", x.rangeBand())
                        .on('click', function(d){
                            scope.showDetails(d, eval('d.'+scope.metric))
                        })

                        // start tooltip
                        .on("mouseover", function(d){
                            console.log("D",scope.metric);

                            var xPos = parseFloat(d3.select(this).attr("x"));
                            var yPos = parseFloat(d3.select(this).attr("y"));
                            var height = parseFloat(d3.select(this).attr("height"))

                            d3.select(this)
                                .append("text")
                                .attr("class", "d3tip")
                                .attr("x",xPos)
                                .attr("y",yPos +height/2)
                                .text("test");
                            })
                        .on("mouseout",function(){
                            d3.select(".tooltip").remove();
                        });
                    // end tooltip

                    // removed data:
                    bar.exit().remove();
                    // updated data:
                    bar
                        .transition()
                        .duration(750)
                        .attr("y", function(d) { return y(eval('d.'+scope.metric)); })
                        .attr("height", function(d) { return height - y(eval('d.'+scope.metric)); });

Answer №1

Thanks to this answer, I was able to achieve my goal.

Here is the solution provided:

var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden");

bar.enter()
    .append("g")
    .attr("class", "bar-container")
    .append("rect")
    .attr("class", "bar")
    .attr('fill','#4EC7BD')
    .attr("x", function(d) { return x(d.id); })
    .attr("y", function(d) { return y(eval('d.'+scope.metric)); })
    .attr("height", function(d) { return height - y(eval('d.'+scope.metric)); })
    .attr("width", x.rangeBand())
    .on('click', function(d){
        scope.showDetails(d, eval('d.'+scope.metric))
    })
    // tooltip
    .on("mouseover", function(d){
        tooltip.text(eval('d.'+scope.metric));
        return tooltip.style("visibility", "visible");
    })
    .on("mousemove", function(){return tooltip.style("top",
            (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
    .on("mouseout", function(){return tooltip.style("visibility", "hidden");});

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

IE8 - "object does not exist or is undefined" error

Below is the HTML code snippet: <td style="vertical-align: bottom;"><div id="resultCount">n.v.</div></td> Accompanied by this JavaScript code: function processResultCount(data) { $("#resultCount").html(formatNumber(data.res ...

JavaScript Regex: Removing all characters that are not numbers

There have been several inquiries about this particular question, such as this one on Stack Overflow. Despite my efforts to replicate the solution and research regex, I can't seem to get it to work: $("#button").click(function () { new_number = $ ...

Is it possible to start the angular-seed project within visual studio?

After cloning the angular-seed repository, I successfully set up an Angularjs app using the following commands: git clone --depth=1 https://github.com/angular/angular-seed.git Web cd Web npm install To start the app, all I had to do was run npm start. H ...

There was an issue with the routing that prevented access to the student activity information at

I've been working on building my own Note Taking App using Express. Following my instructor's example, I wrote some code but encountered an issue when deploying it. Whenever I try to add a new note, I receive an error that says "cannot get/api/na ...

Creating a multi-level signup page in Angular 4 using Bootstrap

Currently, I am working with angular 4 and bootstrap 4 to create a multi-level sign-up page. One of the challenges I am encountering is how to properly include a JavaScript file into my angular project. import '../../../assets/js/js/multiform.js&apo ...

Exploring the basics of AngularJS by creating a straightforward application with a

Hey there, I'm just getting started with AngularJS and I'm trying to organize my JavaScript files into separate functional pieces. I created a controller outside of app.js but unfortunately, it's not working =( Here is the code from app.js: ...

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

Encountering an issue with Firebase authentication in Next.js: the window object is not defined

Here is some code snippets: import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; const firebaseConfig = { //credentials// }; export const ...

Tips for accessing information from an Angular Resource promise

I am currently facing an issue when trying to read data from an angular promise that was returned. Before, I had the following code: var data = category.get({id:userid}); Later, I realized that the data being returned was an unresolved promise. So, I ma ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

After each animation in the sequence is completed, CSS3 looping occurs

I have currently set up a sequence of 5 frames, where each frame consists of 3 animations that gradually fade into the next frame over time. My challenge is figuring out how to loop the animation after completing the last sequence (in this case, #frame2). ...

Observing nested objects in Vue while utilizing deep watching功能

Is there a way to determine which property change in the object triggered the watch call while watching a data object with multiple properties using deep invocation? data(){ return { user:{ first_name:'', last_na ...

Display the list items within a div only if the height is lower than a separate div

I have a scenario where I have two divs named left and right. The left div contains a list of bullets (li elements) and is floated to the left, while the right div has text and HTML content. At times, either the left or the right div may be taller than the ...

What is the procedure for turning off hover color on an href element?

Working on a website that utilizes MUI components, I have incorporated href into the Tab elements within the navigation bar. <Tab label={element} id={index} sx={{display: {xs: 'none', md: 'inherit'}}} href={`#${navElements[element ...

The React-Codemirror highlight matching addon is failing to properly highlight the text

I am currently using react-codemirror and I want to specifically highlight the text 'Hello' within the Codemirror. However, despite using the match-highlighter addon, I am encountering issues with the highlighting. Below is the code snippet that ...

Step-by-Step Guide for Attaching Table Legs

I believe that the four legs should be an integral part of the table, rather than just added on like an afterthought. What would be the best way to create new instances of legs and attach them in a way that makes the back legs look slightly smaller than t ...

The image in drag and drop ghost preview is not appearing on Firefox

I want to show a ghost element instead of the default browser preview while dragging and dropping. However, in Firefox, the image inside the ghost element is not displayed during dragging. Oddly enough, if I drop it and then drag again, the image does appe ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well. After ex ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...