Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

341
Views
Cannot create Chart using Chart.JS @ 2.9.4

I am trying to create a chart using Chart.JS (v2.9.4) but am unable to. Here is the relevant HTML

      <canvas
        id="groupPerformanceChart"
        class="lineClass"
        width="340"
        height="220"
        style="margin-top: 2px; height: 220px; width: 340px;"
      ></canvas>

and here is the relevant JS

  var ctx = $("#groupPerformanceChart");
  if (!ctx) {
    console.log("Context not available");
    return
  }
  else {
    console.log("Context available", ctx)
  }
  let myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: currLabels,
      datasets: dataSet,
    },
    options: {
      responsive: true,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              max: 10,
            },
          },
        ],
      },
    },
  });

and here is what it says in the console:

Context available 
jQuery.fn.init {context: document, selector: '#groupPerformanceChart'}

Failed to create chart: can't acquire context from the given item

Interestingly, the chart shows up sometimes if I trigger HMR in dev environment but obviously this won't work for production. I also have other charts in other places that are created the same way and work fine so this one has me stumped.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is most likely that you have the chart inside a template, which causes it not to be rendered in the moment that you are running the jQuery selector and constructing the chart.

jQuery will always return a value even if no objects have been found. So your check will always say that a context has been found. To fix this, you have to check the length of the jQuery result:

var ctx = $("#groupPerformanceChart");
if (ctx.length <= 0) {
  console.log("Context not available");
  return;
}
else {
  console.log("Context available", ctx)
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!