Issue with Charts.js: The defined moment is missing when using chart.bundle.min.js

I successfully created a chart with charts.js and configured it, but now I aim to make the X Axis represent time. However, when attempting to implement this using the code below, I encounter the following console error: Uncaught ReferenceError: moment is not defined. I am using chart.bundle.min.js which is supposed to include moment.js, so I shouldn't have to separately download and link moment.js.

Here is the code snippet borrowed from a stack member who answered a question regarding the time axis:

function newDate(days) 
{
  return moment().add(days, 'd'); //THE ISSUE ACCORDING TO CONSOLE OCCURS HERE.
};

var config = 
{
  type: 'line',
  data: 
  {
    //Calling the function here also triggers an error in the console.
    labels: [newDate(-4), newDate(-3), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)], 
    datasets: 
    [{
      label: "My First dataset",
      data: [4, 3, 1, 4],
    }]
  },
  options: 
  {
    scales: 
    {
      xAxes: 
      [{
        type: 'time',
        unit: 'month',
      }],
    }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

HTML:

<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <link rel="stylesheet" href="css/customFitStyling.css" type="text/css">
    <link rel="stylesheet" href="css/w3c_v4.css" type="text/css">
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/chart.bundle.min.js"></script>
  </head>
  <body>

    <canvas id="myChart"></canvas>
  </body>
</html>

Answer №1

After examining the situation, it appears that Moment is inexplicably missing from the bundle I utilized. I tested your code on JSFiddle and encountered an error. However, when I loaded Moment.js separately, it functioned perfectly.

Perhaps consider incorporating Chart.js and Moment.js individually instead of using the bundle. If the concern lies with the number of HTTP requests, you have the option to compress and bundle them manually.

Answer №2

After exploring the documentation for charts.js, I discovered that it fully supports all the formats accepted by Moment.js for the time scale data. For more details, refer to the Moment.js documentation.

Therefore, it is recommended to utilize the Chart.js API in this manner:

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        quarter: 'MMM YYYY'
                    }
                }
            }]
        }
    }
})

Instead of using moment().add()

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

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

ReactJS input range issue: Cannot preventDefault within a passive event listener invocation

I've been encountering some issues with the react-input-range component in my React App. It functions perfectly on larger viewports such as PCs and desktops, but on smaller devices like mobile phones and tablets, I'm seeing an error message "Unab ...

AngularJS synchronous $resource functionality allows for the ability to make parallel API

I'm facing a dilemma because I understand that Javascript isn't designed for synchronous work, especially in the case of AngularJS. However, I find myself in a situation where I require it. The main page on the "www" domain (built with AngularJS ...

Alter certain terms in HTML and update background using JavaScript

I want to create a filter that replaces inappropriate words and changes the background color using JavaScript. Here is what I have so far: $(document).ready(function () { $('body').html(function(i, v) { return v.replace(/bad/g, &apos ...

What is the method for retrieving a property from an object contained within an array that is assigned to a property of another object?

How can I retrieve the name property from the subjects array within a course object? The database in use is mongodb. Modifying the course model is not an option. The course model : const mongoose = require('mongoose'); const Schema = mongoose. ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

The PHP table fails to show up on the screen

I've implemented a PHP script that connects to a MySQL database and is supposed to generate an HTML table. To achieve real-time updates, I've set up a long-polling AJAX script that polls the PHP script every second. Although everything seems to b ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

The <script> element failed to close correctly

Within my default.jspx file, which serves as the foundational layout for the page, I am attempting to import several jQuery libraries. The code snippet looks like this: <head> ... <spring:url value="/resources/js/lib/jquery-1.9.1.min.js" ...

Is there a way to convince Python to interpret data as a multi-dimensional list instead of a string when converting from HTML?

Currently, I am working on formatting table data in HTML and then sending it to Python using the script below: var html_table_data = ""; var bRowStarted = true; var count1 = 1 $('#woTable tbody>tr').each(function () { if (count1 != 1) { ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

Drag and release: Place within invalid drop areas

I'm currently developing a drag-and-drop web application using Vue.JS and Vuex Store. The drag-and-drop functionality is based on the HTML Drag and Drop API as outlined in the Mozilla documentation. I have successfully implemented the Dropzone Compone ...

Instructions for adding and deleting input text boxes on an ASP.NET master page

*I am currently facing an issue with adding and removing input textboxes for a CV form using ASP.NET in a master page. Whenever I click on the icon, it doesn't seem to work as intended. The idea is to have a textbox and an icon "+" to add more textbox ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Issues arising with Intersection Observer in vue.js

Recently, I started using IntersectionObserver for the first time and I found a helpful guide at . However, I encountered an error that is causing me some trouble. [Vue warn]: Error in mounted hook: "TypeError: Failed to construct 'IntersectionObserv ...

When the URL is modified, triggering an event to load

Is there a way to make a page load directly to a specific section and automatically open an accordion? For instance, I have a page with multiple accordions displayed vertically. I already know that using id's in the URL like page#accordion1 will scro ...

Can JavaScript be adapted to simulate the features of an object-oriented programming language?

Is there a method in Javascript to imitate an object-oriented language? For example, is it possible to replicate the ability to define custom classes/objects with properties? Given that JSON serves as a means for passing objects in JavaScript, I assume the ...

What could be causing the issue with the JS function that is preventing the button from

I am generating a button dynamically using my JavaScript function and then adding it to the DOM. Below is the code snippet: var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' c ...