Is it possible to retrieve specific information by clicking on an element with the tooltip function in d3 version 6.1.1?

I'm following the migration guide instructions to make the click event display data in the clicked bar, but I can't seem to identify the error in this code snippet: https://codepen.io/bablu4195-1/pen/oNxGWRw

d3.on('click', (event,d,i)=> {
     tooltip.classList.add('show');
     tooltip.style.left = i * barWidth + padding * 2 + 'px';
     tooltip.style.top = height - padding * 4 + 'px';
     tooltip.innerHTML = `<small>${d[0]}</small>$${d[1]} billions`;
     tooltip.setAttribute("data-date", d[0]); 

     })
 .on('click', () => {
        tooltip.classList.remove('show')
}

Answer №1

It appears that there may have been a misunderstanding regarding d3 scaling. Typically, an object is assigned using the .data() method, such as

.data([{ name: 'hello world', value: 12 }])
. However, you utilized scaledGDP, which has resulted in losing other pertinent information and being reduced to just a number. If you utilize GDP instead, you can then access the scaled value by utilizing, for instance,
rect.attr('height', function(d) return linearScale(d); })
.

In addition, it seems that your tooltip did not function as expected due to a couple of issues. Firstly, the usage of on('click') was duplicated - once for adding the tooltip and once for removing it, causing the latter to overwrite the former. Secondly, you treated tooltip as an HTML element when it is actually a d3 selection, so employing .classed() over classList() is more appropriate. Lastly, according to the migration guide, event should now be the first argument within the function, rather than d.

All these points result in the following:

CSS:

#tooltip {
  opacity: 0;
}
#tooltip.show {
  opacity: 1;
}

Javascript

    .on("click", (event, d, i) => {
      if(!tooltip.classed("show")) {
        tooltip.classed("show", true)
          .html(`<small>${d[0]}</small>$${d[1]} billions`)
          .attr("data-date", d[0])
          .style("left", i * barWidth + padding * 2 + "px")
          .style("top", height - padding * 4 + "px");
      } else {
        tooltip.classed("show", false);
      }
    });

The tooltip is operational now and positioned correctly, although the content is not yet populated due to the difference between scaledGDP and GDP.

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

Error encountered while attempting to perform date subtraction (Interpolation not supported)

Hey there, I created a basic function to subtract dates in JavaScript, but I keep getting an error. Here is the JS code: $scope.tosum = function(d1, d2) { var d3 = new Date(d1.getTime() - d2.getTime()); console.log(d3); return d3; }; This is the error ...

What is the process for clearing the input value of a View from another View?

My situation seems simple and straightforward, yet I am struggling to achieve the desired output. In this scenario, I have two HTML pages named Index.htm and Main.htm, as well as a script page named mscript.js. Index.htm contains a button (Clear), and Mai ...

When attempting to load a JSON file, a Node.js loader error is triggered stating "Error: Cannot find module 'example.json'" while running transpiled code through Babel

When it comes to importing or requiring JSON (.json) files in TypeScript code, there have been multiple questions addressing similar issues. However, my query specifically pertains to requiring a JSON file within an ES6 module that is transpiled to the cur ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

Once the <a> element is clicked, ensure that the function finishes executing before attempting to click/process it again

Utilizing jQuery.get for AJAX requests, I trigger a server request when the user clicks on the <a> element. The response is then used to update the content within the <div id='aaa'>. However, if the user clicks on the <a> rapid ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

PHP is adding unique characters like   into the database records

Description : Having an issue with adding a text to a content editable div. When clicking the button, I am trying to extract all the text from the div and send it to php successfully. However, when saving it to my database table, the text gets corrupted. A ...

After passing through JavaScript, my link becomes scrambled

As I'm coding in JavaScript for a website, I've come across a puzzling issue with this string. The troublesome line of code is: var app = "<a onclick='openApp('"+url+"')">"+icon+"</a>" Strangely, when executed, it pr ...

There seems to be an issue with the reduction function in TypeScript, where an element is implicitly assigned the 'any' type due to the type of expression

I'm having an issue with the following code which represents grades of students. let students: { [k: number]: string[] } = {}; students[1] = ["Student 1", "Student 2"]; students[2] = ["Student 3", "Student 4"]; console.log(students); Object.ke ...

JavaScript Flash player for iPad

As many of us know, the iPad does not support Flash. However, I am curious if the iPad sends any specific error messages that can be captured using Javascript. I realize one method is to detect the iPad from the user agent string, but I am interested in w ...

Undefined variables are returned by declarations in a script setup after an asynchronous call with top-level await

Here is the structure of my Nuxt 3 / Vue 3 component using script setup: <script setup> const content = await useFetch('/api/items/published').then((res) => res.data) const items = await content.data.items const issues = awai ...

Tips for implementing Vue in production mode with vue.esm-bundler.js

Currently, I am utilizing Vue 3 with webpack and loading it using vue.esm-bundler.js due to the presence of in-dom templates. The documentation mentions that when using a bundler, you need to "Leaves prod/dev branches with process.env.NODE_ENV guards (mus ...

Make sure to wait for the fetch response before proceeding with the for loop in JavaScript using Node.js

I am facing an issue with my function that connects to a SOAP web service. The problem arises from the fact that the web service has limited connections available. When I use a for or foreach loop to search through an array of items in the web service, aro ...

Error: Unable to assign value to property 'className' of undefined object

On my http://localhost:3000/renewal page, the code looks like this: import Link from 'next/link' export default function Renewal() { return ( <header> <Link href="/"> <a> Go to home page ...

Issue encountered during Node.js installation

Every time I attempt to install node js, I encounter the following errors: C:\Users\Administrator>cd C:/xampp/htdocs/chat C:\xampp\htdocs\chat>npm install npm WARN package.json <a href="/cdn-cgi/l/email-protection" class ...

Save a value outside of a code snippet

In my Play Framework project, I am working with a views .html file where I have the following code snippet: <script type="text/javascript"> setInterval(function() { $.get("file2", function(${list1}, ${list2}, ${list3}){ $("#result").h ...

Leveraging chrome.tabs.executeScript for populating various select options in multi-select fields

Despite my efforts to find a solution on similar posts, I am still struggling to find the specific answer I need. I am currently developing a simple chrome extension that aims to streamline the process of filling out a large form with static information. ...

Enhancing the Wireframe Design

Is there a way to display both the wireframe and the object itself, with vertices that update continuously using a shader? My code currently looks like this; var mainGeo = new THREE.SphereGeometry(100, 80, 80); var shaderMaterial = new THREE.ShaderMateri ...

Querying Using Multiple Filter Selectors

Currently, I am in the process of developing a jQuery multiple filter module and have encountered a logic gap in my framework. Within this module, there are numerous div elements each containing data-x and data-y attributes. For instance: <div class= ...

Is there a way to customize the directory that BABYLON.SceneLoader scans for textures?

Is there a way for me to specify the folder where BABYLON.SceneLoader should look for textures when loading a babylon blender file? Here is an example: BABYLON.SceneLoader.Load("","public/js/corredor.babylon", this.engine, function (newScene) { /*... ...