An error occurs stating 'TypeError: d is undefined' while transitioning on a bar chart triggered by a mouseover event

While working on incorporating transitions into my bar chart, I encountered an issue where they would start from the axis and rise up to the desired height. Although I managed to get the transitions to function properly, the mouseover event stopped working. It's puzzling why d is undefined, considering that I had already appended the data to the plwdhBar object and referenced it later in the code.

After exploring similar solutions, I realized that the key was to first set up the bar chart bars by calling them once with the data, followed by adding the transition and then integrating the mouseover event.

Presently, this is what my code looks like: (the transition works but the mouseover doesn't, resulting in errors for the function showTooltip(d))

var plwdhBar = svg.append("g")
d3.csv("Data/"+name+".csv").then(function(dataset) {
    plwdhBar.selectAll(".plwdhBar") //bar2
        .data(dataset)
        .enter()
        .append("rect")
        .attr("class","plwdhBar")
        .attr("width", 30)
        .attr("fill", bar2Color)
        .attr("x",(d)=>xScale(d.year)+(barW/2)-15)
        .attr("y", h-margin.bottom)
        .transition()
        .duration(200)
        .attr("y",(d)=>yBarScale(d.plwdh))
        .attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)
    plwdhBar.on("mouseover",function(d){
        showTooltip(d);
    }).on("mouseout",function(){
        removeTooltip();
    });
}

I also attempted removing the transition code and simplifying it to:

plwdhBar.transition()
    .duration(200)
    .attr("y",(d)=>yBarScale(d.plwdh))
    .attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)

However, this approach also resulted in an undefined error for d

In all scenarios, the error message reads TypeError: d is undefined. This occurs in the first code snippet when the removeToolTip(d) function is executed, and in the second scenario during the

.attr("y",(d)=>yBarScale(d.plwdh))
line.

Answer №1

Here is the plwdhBar variable:

var plwdhBar = svg.append("g");

This is the extent of it, without any data attached to it. It's crucial to understand this for resolving the issue at hand.

Next, you execute:

plwdhBar.selectAll("plwdhBar")
    .data(dataset)
    .enter()
    .append("rect")
    //etc...

By doing this, you are appending the rectangles, and if you had included the listeners in this chain, it would function correctly. However, remember that this does not alter what plwdhBar represents; it remains simply var plwdhBar = svg.append("g");, as previously established.

So, when you proceed to...

plwdhBar.on("mouseover",function(d){
    showTooltip(d);
})

...an error arises due to the absence of data linked to it.

The solution: assign names to your selections!

For example:

var foo = plwdhBar.selectAll("plwdhBar")
    .data(dataset)
    .enter()
    .append("rect")
    //etc...

Now you can perform:

foo.on("mouseover",function(d){
    showTooltip(d);
})

Nevertheless, there's an important consideration: transitions also utilize a method called on. Therefore, eliminate the transition from the primary chain to avoid encountering another error (independent of the current one). You may incorporate the transition separately:

foo.transition()
    //etc...

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

What is the best way to organize a massive file over 10Gb filled with words?

I've been presented with this interview query: You have an input file containing words (which could be a jumble of letters) separated by commas, and the file size is 10 GB or more. Can you devise an algorithm to sort all these words? Keep in min ...

Exploring the method to retrieve key value pairs within an array object using JavaScript

I have an array of JSON objects and I am trying to extract it as key-value pairs. Here is the code snippet: var fs = require('fs'); var parameters = { 'Tenantid': 'a62b57-a249-4778-9732', "packagecategoryn ...

What is the best way to showcase Angular2 exceptions on my webpage?

In my Angular2 JavaScript code, I am facing an important issue. The priority now is to figure out how to display this error on the Html page. This page will be viewed in a mobile web-view, so it's crucial that developers on the other end can see and u ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Combining arrays by a shared property in JavaScript

My goal is to merge data from two arrays based on the userId. The current solution I have only works efficiently with small datasets, but it becomes impractical with larger arrays due to the excessive use of the filter method. Does anyone have a more effic ...

How can I make the background image of an input text slide out of view when the "Enter" key is pressed?

The code is set up to slide out of view when the user clicks on the image, but I'm unsure how to make it do the same when the user hits "enter" in the input area. It's a bit frustrating... http://jsfiddle.net/mlynn/vxzc6z6y/ JavaScript code: ...

Retrieving a single post from a JSON file using AngularJS

I'm currently delving into AngularJS, but I seem to be stuck on what might be a simple issue. At the moment, I have some hardcoded JSON files with a few persons in them and no actual backend set up yet. In my form, I aim to display a single person ea ...

Error encountered while using AngularJS and Node.js with the 'phantom' node module. The application is throwing an injection error as AngularJS attempts to load a directive with a suffix

Upon loading an AngularJS page, everything proceeds smoothly with no console errors and the content displays as expected. However, encountering a different scenario where attempting to load the same page from another application using the Node module &apo ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

Looping through objects and updating state based on a filter condition

Within my React state, there exists an array of objects similar to the following: timers: { id:"-LL-YVYNC_BGirSn1Ydu" title: "Project Title" project: "Project Name", elapsed: 0, runningSince: 0, }, { id:"-LL-YVYNC_BGirSn1Ydu-2", ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

In what way can a Knockout.js action be executed prior to navigating to an <href> link?

While working with knockout.js and Html5, I encountered an issue that I haven't been able to resolve. The main objective is to trigger a click-binding just before navigating to another page via an Href link. This click-binding involves an ajax method ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

detecting a click event on a div element with no content and a

There are three divs in the code snippet below: You can view the code on JSFiddle. $(document).on('click', '.top', function (e) { console.log("Empty space clicked"); }); .top{ width: 208px; text-transform: uppercase; ...

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 ...

React array fails to update upon modification

Hey there! I've created a component that takes an array of strings, combines them, and then renders a typing animation by wrapping each character in a span tag with toggling opacity from 0 to 1. I noticed an issue when switching the order of displaye ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Can a C# MVC List<int> be transformed into a JavaScript array?

Can a MVC C# List be converted to a JavaScript array? var jsArray = @Model.IntList; I would really appreciate any assistance on this matter. ...

Nested variable declarations within block scoping can result in various types of errors

I'm currently exploring the concept of block scoping in ES6 and encountered an interesting issue that I need help understanding: In my initial test, I attempted the following code snippet and observed the error mentioned within the comments: { c ...