Eliminating error messages that appear when a user clicks on a legend label

Within my Laravel 5.7 application, I am utilizing Chart.js version 2.7.2 for a Stacked Line chart feature that opens a modal dialog when a user clicks on points within the report.

    var lineCanvas = document.getElementById("canvasVotesByDays");
    var lineCanvasContext = lineCanvas.getContext('2d');
    $("#div_canvasVotesByDays").css("display", "block")

    var numberWithCommas = function (x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };
    var self = this;

    if (window.chartLineObject != undefined) { // clear existing instance
        window.chartLineObject.destroy();
    }

    window.chartLineObject = new Chart(lineCanvasContext, {
        type: 'line',
        data: {
            labels: monthsXCoordItems,
            datasets: [
                {
                    label: 'Correct Votes',
                    data: voteValuesCorrect,
                    borderWidth: 1,           // The stroke width of the line in pixels.
                },
                {
                    label: 'Incorrect Votes',
                    data: voteValuesNoneCorrect,
                    borderWidth: 1,           // The stroke width of the line in pixels.
                }
            ]
        },

        options: { // options of Report By Vote Days ( 'line' report )
            animation: {
                duration: 10,
            },

            tooltips: { // tooltip text of Report By Vote Days ( 'line' report )
                mode: 'label',
                callbacks: {
                    label: function (tooltipItem, data) {
                        return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
                    }
                }
            }, // tooltips: { // tooltip text of Report By Vote Days ( 'line' report )

            scales: { // options for x and y scales of 'line' report
                xAxes: [{
                    stacked: true,    // Stacked line charts can be used to show how one data series i
                    gridLines: {display: true},
                }],
                yAxes: [{
                    stacked: true,  // Stacked line charts can be used to show how one data series i
                    ticks: {
                        callback: function (value) {  // on Y scale show only integer without decimals
                            if (Math.floor(value) === value) {
                                return value;
                            }  // return numberWithCommas(value);
                        },
                    },
                }],
            }, // scales: { // options for x and y scales of 'line' report
            legend: {display: true}
        } // options: { // options of Report By Vote Days ( 'line' report )

    }); // window.chartLineObject = new Chart(lineCanvasContext, {

    lineCanvas.onclick = function (e) {
        var firstPoint = window.chartLineObject.getElementsAtEvent(e);
        if (typeof firstPoint[0] == "undefined") {
            popupAlert("Select one of visible dots to get detailed results !", 'danger')
            return;
        }
        if (firstPoint) {
            var first_point_index = firstPoint[0]._index
            if (typeof window.chartLineObject.data.labels[first_point_index] == "undefined") {
                popupAlert("Bad point !", 'danger')
                return;
            }

            var selected_day = window.chartLineObject.data.labels[first_point_index];
            backendReports.showVoteNamesReportDetailsByDays(selected_day)
            return;
        }
    } // window.chartLineObject.onclick = function(e) {

The main purpose of this functionality is to trigger a dialog model specifically when the user interacts with visible points on the report. While the functionality operates correctly, an issue arises when attempting to click on the legend block situated at the top of the report (which also functions as a filter), resulting in an error message:

https://i.sstatic.net/VZBAh.jpg

Is there a way to differentiate between clicking on the legend label versus other areas?

You can interact live with this feature at

Thank you!

Answer №1

Have you considered combining the chart onclick event with the canvas onclick? The canvas onclick function includes a filter feature, while the chart onclick can display a modal.

    onClick: function(c,i) {
            e = i[0];
            var x_val = this.data.labels[e._index];
            var y_val = this.data.datasets[0].data[e._index];
            var ID = x_val;
            var Tip = 1;

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

Can you tell me the alternative for window.location.href when using Vue router?

After performing an action in my Vue app, I am looking to redirect to a different page within my single-page application (SPA). However, when I use the code window.location.href = "/subpage", the page refreshes and I end up losing cached data tha ...

Ensure that the "Read more" button appears on the same line as the truncated text after a specified number of lines

I am working on getting the Read more feature to appear on the same line as the truncated text after a certain number of lines. Currently, it is showing up below the truncated text. <p style={{ overflow: 'hidden', display: '-webkit-box&ap ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

When displaying text pulled from MYSQL in a div, white space is eliminated

I'm attempting to display a string that contains both spaces and line breaks. When I output the string as a value in an input field, the spaces are displayed correctly. <textarea rows={15} value={content} /> However, when I try to display ...

Issue with Chart.JS bar chart displaying error related to missing parenthesis

I am struggling to create a bar chart and can't seem to figure out the correct syntax. Every time I try, I encounter this error: Uncaught SyntaxError: missing ) after argument list The error seems to be on this line label: 'Dollar Values&apos ...

The autofill ajax script is unable to populate dynamically added rows

As a newcomer to programming, I am trying to create a table that allows users to add new rows by clicking a button. Each row should have a field for inputting an ID which corresponds to some predefined numbers in another table, and then the other field sho ...

Extract individual export icons from the React icon library

I've recently put together an icon package and am ready to share it with the world under the name @rct/icons. Here's a glimpse at my package.json: { "name": "@rct/icons", "version": "1.0.0", "sc ...

Minimize MongoDB aggregation using specific criteria

I am facing a challenge with my array of objects named "extra" that have different properties: some objects include the property "plus" while others do not. I am attempting to split this "extra" array into two separate arrays - one called "cheap" containin ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

What significance does this terminal hold? (utilizing Next.js next/router)

Currently, I am in the process of developing a portfolio website using Next.js and tailwind css with ReactJs (without typescript). One issue that I encountered was with the Router(next/router) functionality. Despite my attempts to find a suitable sample, c ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...

Simulate a left mouse click on the swf object once the page has fully loaded

My website now features a flash game that inexplicably requires a left mouse click on the page after loading in order to enable arrow key functionality. I attempted using a JavaScript-based mouse trigger in my HTML code and assigned an ID to the flash obj ...

YouTube's embedded video player is invincible and cannot be destroyed

Having trouble destroying an embedded YouTube video on the Plyr player. The player.destroy() method is being called without any errors, but it doesn't actually destroy the player. This issue is causing the previous video to load instead of a new one ...

Protractor - Chrome is denying access to this webpage when attempting to access it automatically

Currently, I am familiarizing myself with Protractor as the tool for automating website testing. Specifically, I am running tests on the following page: , using Google Chrome browser. The issue at hand is: 1. Protractor successfully navigates to . 2. Ma ...

What could be causing the hover effect to not work on the cards in my Svelte component? (HTML+CSS)

Greetings everyone! This is my debut post on this platform, and I'm in urgent need of assistance as I am relatively new to the world of programming. I've been trying tirelessly to implement a hover effect on these cards, but for some reason, it ...

Is it possible to transfer a variable to a modal window by clicking on a link?

Here is a link with sample data value "data-id" that I want to pass: <a href="#edit_task" data-toggle="modal" data-id="WAH"><i class="fas fa-edit fa-lg fa-fw"></i></a> Javascript code to open the modal and assign the data value to ...

Retrieving information upon page loading and setting it as select options within a Vue JS environment

Currently, I am working on a straightforward form that includes a select type form. This specific form is initially created without any options as I intend to dynamically populate them from the backend later. Below is the code snippet for reference: < ...

Issue with React component not updating

Experiencing an issue in a React code related to nested components within React. Link to code The problem arises from having a parent component called "testing" with two child components, Component1 and Component2, each with Component3 as a sub-child und ...

Why are the elements not found by their id when I check them, even though they were created dynamically using an ajax-generated form with php-inserted values through a

How can I prepopulate form fields displayed in a modal view using jQuery after retrieving the form HTML with an AJAX query? I am trying to set the values through a JavaScript function that retrieves PHP-generated values via document.getElementById. However ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...