Has anyone else encountered an unexpected issue while using the "mouseover" listener in D3.js? I could use some suggestions on how to troubleshoot this

Encountering an issue when hovering over the circle SVGs in my browser:

"Uncaught TypeError: Cannot read property '#<Object>' of undefined
    at SVGCircleElement.<anonymous> (app.js:35)
    at SVGCircleElement.<anonymous> (d3.v6.min.js:2)"

Suspect it relates to the 'n' parameter or the "mousover" component. Interestingly, when using console.log(n) or console.log(n[0]) in a callback function other than mousover's, n is recognized without throwing an error.

Here's my app.js code:


    const canvas = d3.select(".canva");
    
    const svgWidth = "100%";
    const svgHeight = "100%";
    const api_url =
    
    "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson";
    
    const svg = canvas
        .append("svg")
        .attr("width", svgWidth)
        .attr("height", svgHeight);
    
    d3.json(api_url).then((data) => {
        //in this fn we put our data together
    
        const circle = svg
            .selectAll("circle")
            .data(data.features)
            .enter() //enter
            .append("circle"); //append combo
    
        circle
            .attr(
                "cx",
                (d, i) => 40 + Math.floor(Math.random() * 110 * d.properties.mag)
            )
            .attr("cy", (d, i) => 40 + Math.floor(Math.random() * 200))
            .attr("r", (d, i) => d.properties.mag * 4)
            .attr("fill", "black") //default fill
            .attr("fill", (d, i, n) => d.properties.alert)
            .style("top", 150)
            .on("mouseover", function (d, i, n) {
                d3.select(n[i])
                    .transition()
                    .duration(100) //millisecs
                    .style("opacity", 0.7);
            });
    });

Data retrieved from USGS API:


    {
        "type": "FeatureCollection",
        "metadata": {
            "generated": 1607915888000,
            "url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson",
            "title": "USGS Significant Earthquakes, Past Month",
            "status": 200,
            "api": "1.10.3",
            "count": 9
        },
        "features": [
            {
                "type": "Feature",
                "properties": {
                    "mag": 6.1,
                    "place": "25 km E of Yilan, Taiwan",
                    "time": 1607606398910,
                    "updated": 1607782466973,
                    "tz": null,
                    "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us7000cpqz",
                    "detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us7000cpqz.geojson",
                    "felt": 237,
                    "cdi": 5.5,
                    "mmi": 5.056,
                    "alert": "green",
                    "status": "reviewed",
                    "tsunami": 0,
                    "sig": 703,
                    "net": "us",
                    "code": "7000cpqz",
                    "ids": ",us7000cpqz,",
                    "sources": ",us,",
                    "types": ",dyfi,ground-failure,losspager,moment-tensor,origin,phase-data,shakemap,",
                    "nst": null,
                    "dmin": 0.51,
                    "rms": 0.74,
                    "gap": 18,
                    "magType": "mww",
                    "type": "earthquake",
                    "title": "M 6.1 - 25 km E of Yilan, Taiwan"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        122.0098,
                        24.7632,
                        73.17
                    ]
                },
                "id": "us7000cpqz"
            },
            ...
            truncated for brevity
        ],
        "bbox": [
            -168.2667,
            -34.5982,
            4.95,
            140.7971,
            52.7655,
            589
        ]
    }

View index.html below:


    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>D3 Intro</title>
            <link rel="stylesheet" href="main.css" />
            <script src="https://d3js.org/d3.v6.min.js"></script>
        </head>
        <body>
            <div class="canva"></div>
    
            <script src="app.js"></script>
        </body>
    </html>

Answer №1

After investigating Andrew Reid's observation, it turns out there was indeed a version compatibility issue. In light of that, I made the necessary adjustment by updating the following code snippet:

    .on("mouseover", function (d, i, n) {
        d3.select(n[i])
            .transition()
            .duration(100) //milliseconds
            .style("opacity", 0.7);
    });

to this revised version:

    .on("mouseover", function () {
        d3.select(this)
            .transition()
            .duration(100) //milliseconds
            .style("opacity", 0.7);
    });

The updated code now operates as intended.

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

When attempting to print the content inside a Bootstrap modal, the display does not appear but instead a blank page is printed

My goal is to print the text content of a bootstrap modal while leaving space for images blank when clicking the print button located within the modal. Unfortunately, upon clicking the print button, I am only getting a blank page without any content displ ...

What is the optimal method for iterating through a nested array?

I've been searching like this for quite some time now, and it seems there must be a more efficient approach. The scenario is that I have a double elimination tournament bracket and need to locate a specific game. The brackets for winners and losers ar ...

JavaScript functions with identical names

When attempting to write a function with the same name in both a JS file and on a page, an error was expected but did not occur. Only the function from the JS file executed. This raises the question of how this is possible. Despite separate JS files being ...

Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu. Here is the sample code: HTML: <select ng-model='theModel' ng-change="display(theModel)" > <optgroup ng-repeat='group in collectio ...

Efficient Checkbox Implementation in ActiveAdmin for Rails 3.1

This query actually encompasses two related inquiries. Enabling "Select all" functionality - In the realm of formtastic, which is used by Active_admin to render forms, how can I implement a button that selects all checkboxes present on the page? While ...

Is it possible to utilize Socket.io for communication between two separate localhost ports?

Today marks my first encounter with Socket.io. I have structured a chat application that spans across two separate files, server.js and pi.js, each hosted on distinct ports (server on 3000, pi on 3001). For guidance, I've been following the tips provi ...

The Vue app for logging in with Metamask is unable to communicate with the Metamask extension due to a lack of interaction between the store components and the frontend interface

After following a tutorial to create a Metamask login app with Vue, I ran into some issues. The code provided lacked a defined project structure, so I decided to organize it in my own Github repo here. However, despite compiling successfully, the button to ...

Guide to creating a Javascript API wrapper

I'm currently working on a React client and I have a question regarding the implementation of a JavaScript wrapper. The APIs I am using return more data than is necessary for the client, so I want to create an index.js file where I can call the API, r ...

Transferring JavaScript to a different page using EJS

Feeling a little stuck here and could use some assistance. It seems like a simple issue, but I'm tired and could really use a fresh pair of eyes to take a look. I'm trying to pass the 'username' variable, but since I'm new to this ...

What is the best way to extract targeted JSON data from a REST API with Node.js?

I am struggling to retrieve JSON data for a specific match, let's say match=2, from a collection of matches stored in MongoDB. Here is a sample of the JSON response: { "_id": "5a63051735aaddd30d1d89cc", "id": 1, "season": 2008, "city ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Steps for sending Ajax data to your server in order to make changes to your SharePoint list information

After spending a considerable amount of time working on my DataTable, I've managed to incorporate all the necessary functionalities except for one. Currently, my table retrieves data from a SharePoint list through an AJAX "GET" Request and organizes i ...

Error: Attempting to destructure the 'recipes' property from 'props' results in a TypeError due to its undefined value

I am new to working with reactjs and encountered an error when trying to run a program. The specific error message is as follows: Uncaught TypeError: Cannot destructure property 'recipes' of 'props' as it is undefined. at RecipeList ...

Calculate a new value based on input from a dynamic textbox within a datatable when a key is pressed

This question is a follow-up from the following solved queries (please do not mark it as a duplicate): jquery: accessing textbox value in a datatable How to bind events on dynamically created elements? I have generated a dynamic textbox within a dat ...

Refresh the texture mapping within ThreeJS

Hey there! Just wanted to share that I was able to find a solution by using mesh.material.map.image.src = texture; Here was the original question: I'm working on a ThreeJS project and I'm trying to change the texture on a mesh. Unfortunately, I ...

The function wp_register_script is designed to accept only two arguments

For hours, I struggled to include a custom JavaScript file in my child theme. Eventually, I managed to make it work using this piece of code: wp_register_script( 'resources-page', get_stylesheet_directory_uri() . '/layout/js/resources_pag ...

Directing traffic from one webpage to another without revealing the file path in the Routes.js configuration

Recently starting out in Reactjs and utilizing Material-UI. My inquiry is regarding transitioning between pages using a sidebar, where in Material-UI it's required to display the page in the sidebar which isn't what I desire. var dashRoutes = [ ...

[Electricity Boost]eliminate element from array using a variable value given in key and value structure

Currently, I am attempting to eliminate an element from an array if it holds a specific value for a fixed key. Below is the initial input: { "components": { "schemas": { "element1": { "type": &quo ...

Unable to save canvas as an image due to tainted canvas in a React application

I encountered an error after the line containing canvas.toDataURL(). An error message stating "Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvas may not be exported" was displayed. Despite attempting to search for ...

Transforming HTML code into a structured object

The provided code snippet includes HTML markup that needs to be transformed into a specific format. <html> <head> <title>Hello!</title> </head> <body> <div class=”div1”> <h1>This is a ...