"Graphs not Displaying Properly in ChartJs

Seeking assistance with rendering a chart inside a bootstrap popover. Despite various debugging attempts, the chart refuses to render. Any help or insight would be greatly appreciated. Below is my HTML code:

<div id="popover-content" style="display: none;">
      {%include 'scroll_card.html'%}
    </div>

Note: I am using Jinja to render the HTML containing the graph intended for display in the popover. Below is the content of the scroll_card.html file:

  <div class='summary'><h5 class='header'> Chart </h5>
        <div class="chart" style="height: 400px;">
        <canvas id='hourly-chart' width="300" height="400">Hello</canvas></div>
    </div>

And here is my JavaScript code:


document.addEventListener('DOMContentLoaded', function() {
const myPopoverTrigger = document.getElementById('popover');
let hourChart =null;
const instance = new mdb.Popover(myPopoverTrigger, {
    title:"Hourly Forecast",
    sanitize:false,
    html:true,
    content: function(){
        popContent = document.querySelector('#popover-content').innerHTML;
        return popContent;
    }
    
});


myPopoverTrigger.addEventListener('show.mdb.popover', () => {
    const ctxHour = document.getElementById('hourly-chart').getContext('2d');
    console.log(ctxHour);
    if (hourChart) {
            hourChart.destroy();
        }
hourChart = new Chart(ctxHour, {
    type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        }]
      },
      options: {
        responsive: false,
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    
    });
    console.log(hourChart);
});
    myPopoverTrigger.addEventListener('hide.mdb.popover', () => {
        if (hourChart) {
            hourChart.destroy();
        }

    });
});

Furthermore, when I use console.log on the chart (hourChart), it returns some unexpected attributes such as x and y being undefined in the options section. Could I be overlooking something or making an error?

Thank you.

Edit:

Upon calling console.log(hourChart), my console displays the following:

https://i.sstatic.net/u6iRm.png

Answer №1

To ensure that the canvas/chart renders correctly, it is essential to provide the HTML content directly within the option. Otherwise, the content may not be added to the DOM in time for rendering.

const instance = new mdb.Popover(myPopoverTrigger, {
        title: "Hourly Forecast",
        sanitize: false,
        html: true,
        content: `<div id="popover-content">
                <div class='summary'>
                    <h5 class='header'> Chart </h5>
                    <div class="chart" style="height: 400px; width: 600px;">
                        <canvas id='hourly-chart' width="600" height="400"></canvas>
                    </div>
                </div>
            </div>`

    });

Check out the demo:

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 there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Guide to making a slider menu using html, css, and javascript

Just dipping my toes into the world of web development. I'm intrigued by the idea of creating a "slider menu" where users can view and select options by clicking on next or previous buttons (see example image below). While I've got some basic HTM ...

JavaScript code that is condensed for efficiency without sacrificing readability and maintainability

As a novice in the world of javascript, I find that studying pre-existing code helps me learn a great deal. I've encountered some extensive javascript projects with minified code that becomes almost indecipherable when expanded. Most variables and f ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

What is the best way to view and use the data stored within this JSON object?

Obtaining information from a straightforward API (). I retrieve the data using getJSON: var police = $.getJSON(queryurl); A console.log on police displays this: https://i.sstatic.net/Kjyz8.png However, I am unable to access the properties within the o ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

Monitoring the modifications of a linked component in React: A guide

I am facing an issue where I need to store the text of a referenced element in an array. My goal is to first display the text of each paragraph element with the "ebookName" class in the console before storing it in the array. However, I have encountered a ...

Pattern to identify a 32-character string comprising a mix of letters and numbers

I am in search of a JavaScript regex pattern that can identify strings with the following format... loYm9vYzE6Z-aaj5lL_Og539wFer0KfD pxeGxvYzE6o97T7OD2mu_qowJdqR7NRc gwaXhuYzE6l3r1wh5ZdSkJvtK6uSw11d These strings are always 32 characters long and conta ...

Utilizing Vue JS for filtering numerical data

When I search for letters, my code below works well. However, when it comes to numbers like flat_number, it gives me an error saying flat.flat_number.toLowerCase is not a function filteredList() { return this.Flats.filter((flat) => { return ( ...

Decoding a barcode using JavaScript

Currently, I am facing an issue with my barcode gun scanner. It reads barcodes into input fields but returns each digit separately instead of as a whole string. This has been quite bothersome for me. For instance, when I scan the barcode of a bottle of wa ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

The CSS style of the Div element is not being displayed properly when embedded with JavaScript

Currently, I am working on a simple page for practice purposes. The main issue I am facing is with a div element that has a red border and a blue background. Inside the div, there is a script tag calling an external JavaScript file. Surprisingly, the JavaS ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Enhancing Google Custom Search Engine with Bootstrap3 and CSS3 styling

I'm looking for guidance on how to customize the appearance of a Google Custom Searchbar on my website. Is it feasible to style it using CSS3 and Bootstrap 3 like the example in the image below? Any assistance is greatly appreciated. ...

Having trouble getting Javascript Jquery to function properly?

There is a button that, when clicked, changes the HTML in the body tag to include a new button. However, when this new button is clicked, it should trigger an alert message but it is not working as expected. I suspect that the issue lies with the document ...