Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4.

// Enter Phase
this.chart.selectAll('.bar')
  .data(this.barData)
  .enter()
  .append('rect')
  .attr('class', 'bar');

// Update Phase
let bars = this.chart.selectAll('.bar').transition()
  .attr('x', (d) => {return this.x(this.parseTime(d.date.toUpperCase()));})
  .attr('y', (d) => {return this.y(d.point)})
  .attr('width', 15)
  .attr('height', (d) => {return this.charDimensions.height - this.y(d.point);})
    .on("mouseover", function (d) {D3.select(this).style('opacity', 0.5);})
    .on("mouseout", function (d) {D3.select(this).style('opacity', 1);})
    .on("click", (d) => {this.barClicked.emit(d);});

// Exit phase
this.chart.selectAll('.bar')
  .data(this.barData)
  .exit().remove();

While implementing my plotting method, I encountered an issue where calling animate() resulted in the error: Error: unknown type: mouseover. This is likely due to attempting to apply the on("<event>") method on a transition object returned by D3. The transition effect works, but everything after it breaks, causing incorrect plotting.

When trying the following instead:

// Update Phase
let bars = this.chart.selectAll('.bar');
bars.transition();
bars.attr('x', (d) => {return this.x(this.parseTime(d.date.toUpperCase()));})
  .attr('y', (d) => {return this.y(d.point)})
  .attr('width', 15)
  .attr('height', (d) => {return this.charDimensions.height - this.y(d.point);})
    .on("mouseover", function (d) {D3.select(this).style('opacity', 0.5);})
    .on("mouseout", function (d) {D3.select(this).style('opacity', 1);})
    .on("click", (d) => {this.barClicked.emit(d);});

No errors are thrown, but there is no transition effect applied to the new dataset.

Answer №1

There seems to be a mix-up between two distinct methods that share the identical name:

When working with a transition selection and using...

.on(...

The method requires three specific typenames:

  • "start"
  • "end"
  • "interrupt"

However, "mouseover", "mouseout" or "click" are not valid in this context, leading to the error message...

> Uncaught Error: unknown type: mouseover

To resolve this issue:

Attach event listeners to a standard selection first, before creating the transition selection.

In your scenario, bind all on listeners to the "enter" selection instead of the update selection for better clarity.

Check out this example below. First, establish a regular enter selection with an event listener:

var bars = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    //add some attributes here
    .on("mouseover", function(d) {
        console.log(d)
    });

Then, introduce the transition:

bars.transition()
    .duration(1000)
    etc...

Hover over the bars to observe the "mouseover" event in action:

var svg = d3.select("svg");
var data = [30, 280, 40, 140, 210, 110];
var bars = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("x", 0)
  .attr("width", 0)
  .attr("y", function(d, i) {
    return i * 20
  })
  .attr("height", 18)
  .attr("fill", "teal")
  .on("mouseover", function(d) {
    console.log(d)
  });

bars.transition()
  .duration(1000)
  .attr("width", function(d) {
    return d
  })
.as-console-wrapper { max-height: 25% !important;}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

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

Is it possible to communicate with a native chat application such as Pidgin using Node.js?

Is there a seamless way to connect with a native messaging client like Pidgin using Node.js? I attempted to develop a basic chat system utilizing the XMPP protocol in conjunction with Node.js (using https://github.com/astro/node-xmpp followed by https://g ...

Products failing to appear in shopping cart

I'm facing an issue with my React Redux Cart setup where items are added to the cart state using the addItem action, but they do not appear on the Cart page. Challenge: After adding items to the cart through the addItem action, I can see the state u ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

Trigger Ajax POST on modal close button click

I am facing an issue with my modal where it still performs an Ajax post even after clicking the 'Close' button. I want to prevent the Ajax post when the user clicks on 'Close'. Any suggestions on how to handle this situation? Modal &l ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

How to prevent users from selecting certain options using angular's ng-options

As per the Angular documentation ng-options guidelines I tried to implement this piece of code: <select ng-model="model" ng-options="item.CODE as item.NAME disable when item.DISABLE for item in list" id="foo" name="foo" ng-change="change()"> Howe ...

A div element without a float property set will not automatically adjust its

Can someone help me with this issue? The left-menu div is not the same height as the main content. I've tried using overflow, but it just adds a scroll bar. I've looked at numerous posts on Stack Overflow, but I can't seem to fix this proble ...

Next.js fails to update the user interface (UI) when there is a change in

In my latest Next.js project, I am working on a feature that involves looping through an array of amenities. Each amenity is displayed in a div element that, when clicked, toggles the active property. The logic behind this functionality is handled by the ...

Wrapping HTML input elements in a div for alignment

I need help aligning the inputs in my form to match the image provided https://i.sstatic.net/AXhlp.png. I attempted to center the div using <center>, but I am unsure how to properly align the elements based on the image reference. <center> ...

Merge identical data into a unified field within a table

I have a table that displays different colors and their quantities. I would like to merge rows with the same color into one row, with the total quantity shown in that row. For instance, if there are 2 "black" colors with quantities of 5 and 2, I want to c ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my ...

The PDF file appeared blank after receiving a response from the API using Node.js

When I call a REST API that returns a PDF file, the document appears blank when opened. The console indicates that the data may be corrupted. let url ="API-URL"; var options = { 'method': 'GET', 'url': url ...

The React application deployed on GitHub Pages is displaying a blank white screen

I developed a simple meme generator app in React.js as an exercise to learn web development, but I am facing issues while trying to host it on Github pages. I followed all the necessary steps such as installing gh-pages with node, updating packages.json wi ...

Using Twitter Bootstrap and jQuery UI modal within an mvc4 framework

I successfully integrated jQuery UI scripts for modal and datepicker into the generic MVC4 template view. However, when I tried to include Twitter Bootstrap layout as well, the datepicker and modal elements were not displaying properly. Additionally, I enc ...

Performing an AJAX Post request with Jquery in a Ruby on Rails web

Using a straightforward controller setup: def new @product = Product.new respond_to do |format| format.html #new.html.erb format.json { render json: @product} end end def create @product = Product.new(params[:product]) ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

Unclear about how inheritance works with the general sibling combinator "~" (tilde)?

When attempting to color list items in an unordered list using the general sibling combinator, nothing seems to happen: http://jsfiddle.net/bkbehpv0/ p { color: blue } h1 ~ li { color: red; } <h1> Title of site </h1> <p> Text in t ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...