"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four.

Currently, the chart animates upon loading. How can I make it so that when #chartTrigger (Tab Three) is clicked, a new chart is generated?

Furthermore, is there a way to limit the number of animations? For instance, if a user switches to Tab Four and then returns to Tab Three, can we prevent the animation from replaying?

You can preview what I have implemented here: https://codepen.io/drewalth/pen/wppNbJ

<style>
body {
  font-family:sans-serif;
}

div.tab button {
   border: none;
   outline: none;
   cursor: pointer;
   padding: 0.6em 1em;
   flex-basis: 12%;
   color: #34495E;
    letter-spacing: 1px;
   text-transform: capitalize;
    font-size: 0.9em;
    background-color: #BDC3C7;
}
div.tab button.active {
    background-color: #34495E;
    color:#fff;
}

.tabcontent {
  display: none;
  height:300px;
  width:50%;
  color:#fff;
  padding:35px;
}

#tabOne {
  background-color:#E74C3C;
}
#tabTwo {
  background-color:#3498DB;
}

#tabThree {
  text-align:center;
}

#tabFour {
  background-color:#2ECC71;
}


</style>

<div class="tab">
            <button id="defaultOpen" class="tablinks" 
onclick="openTab(event, 'tabOne')">Tab One</button>
            <button class="tablinks" onclick="openTab(event, 
'tabTwo')">Tab Two</button>
            <button id="chartTrigger" class="tablinks" 
onclick="openTab(event, 'tabThree')">Tab Three</button>
            <button class="tablinks" onclick="openTab(event, 
'tabFour')">Tab Four</button>

        </div>
<div id="tabOne" class="tabcontent">
  Click Tab Three for Chart
</div>
<div id="tabTwo" class="tabcontent">

</div>
<div id="tabThree" class="tabcontent">
  <canvas id="test-chart" height="500"></canvas>
</div>
<div id="tabFour" class="tabcontent">

</div>
<script>

// function to switch between tabs

function openTab(evt, tabName) {

  var i, tabcontent, tablinks;

  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";
}

document.getElementById("defaultOpen").click();

// Working Chart.js

var ctx = document.getElementById("test-chart").getContext('2d');
    var newTestChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["10/21", "10/22", "10/23", "10/24", "10/25", "10/26", 
"10/27", "10/28", "10/29", "10/30", "10/31", "11/01", "11/02", "11/03", 
"11/04"],
        datasets: [{
          data: [150, 550, 500, 880, 200, 100, 102, 102, 99, 105, 100, 
103, 100, 102, 100],
          backgroundColor: ['rgba(77, 112, 144, 0.4)', ],
          borderColor: ['rgba(77, 112, 144,1)', ],
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        defaultFontFamily: "'Titillium Web'",
        defaultFontSize: 16,
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        },
      }
    });



// Desired functionality...

var $chartTrigger = document.getElementById("chartTrigger");

$chartTrigger.onclick(newChart);

</script>

Answer №1

To optimize the chart loading process, it is recommended to move the chart code inside the openTab function and utilize a global variable as a flag. This flag can be used to determine if the chart has already been loaded, in which case it does not need to be loaded again. You can refer to the CodePen demo provided below for implementation details.

// switch between tabs
var isLoaded = false;

function openTab(evt, tabName) {

  var i, tabcontent, tablinks;

  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";

  if (tabName == 'tabThree' && !isLoaded) {
    isLoaded = true;
    // Working Chart.js
    console.log('loaded');
    var ctx = document.getElementById("test-chart").getContext('2d');
    var newTestChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["10/21", "10/22", "10/23", "10/24", "10/25", "10/26", "10/27", "10/28", "10/29", "10/30", "10/31", "11/01", "11/02", "11/03", "11/04"],
        datasets: [{
          data: [150, 550, 500, 880, 200, 100, 102, 102, 99, 105, 100, 103, 100, 102, 100],
          backgroundColor: ['rgba(77, 112, 144, 0.4)', ],
          borderColor: ['rgba(77, 112, 144,1)', ],
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        defaultFontFamily: "'Titillium Web'",
        defaultFontSize: 16,
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        },
      }
    });


  }
}

document.getElementById("defaultOpen").click();
...

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

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

Leverage Jquery within the div element to manipulate the data retrieved from a post ajax request

On my one.jsp page, I have the following post code: $.post("<%=request.getContextPath()%>/two.jsp", { vaedre: fullDate} ,function(result){ $("#theresult").append(result); }); This code generates the followi ...

Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected: function fetchViewModelFromServerAsync(){ setTimeout(function(){ ...

Bootstrap Table with Numerous Rows and Columns

I am striving to create a table layout similar to the one shown in the image using bootstrap 5. https://i.sstatic.net/lEnYX.png My attempt so far looks like this <table class="table table-bordered"> <thead> <tr> ...

Creating a unique handle for resizing in jQuery UI's resizable()

Take a look at the JSFiddle link provided. I've been able to successfully use the resizeable() function without any issues when using the default handler. However, when I try to specify a custom handler, the box doesn't resize as expected - even ...

Setting up of imagemagick node module using linuxbrew

Having trouble installing imagemagick-native as it's showing an error. Tried using the following command to install: npm install imagemaick-native --save > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c45414d ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...

What reasons might lead an object to be passed to a view as the exact term 'object' in Express.js?

Using nodejs, express, and ejs. I have a variable called 'result' which is properly defined. When I use console.log(result) within the router.get function on my index page, it outputs a correctly structured array of objects. After that, I rende ...

Tips for adding your artistic touch to photos

I'm currently facing a challenge in creating a chart that overlaps an image. The bars and text on the chart are displaying perfectly when I remove the background image. However, I'm struggling to get the bars and text to appear on top of the imag ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

An Overview of Implementing Ajax Calls for Partial Views on Form Submission

Check out my jQuery code below: <script type="text/javascript"> $("#submitfileform").submit(function () { $.ajax({ type: 'POST', contentType: 'application/html;charset=utf-8', dataT ...

The customized sweet alert button is failing to trigger its designated function

I integrated vue-swal to show a pop-up dialog with customized functionality. However, I faced an issue while modifying the swal. In my modified version, there are 3 buttons each with specific actions that should be triggered upon clicking. But for some rea ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

"Unprecedented occurrence of double events firing in jQuery's sortable and draggable functions

I've implemented some drag and drop code that is functioning properly. However, I have encountered a minor issue. Whenever I add an alert within the drop function for debugging purposes (e.g. alert(draggedItem.text());), it triggers the alert twice wh ...

Numerous operations included in a JavaScript document

Looking to enhance my JS file by adding multiple functions, but I'm having trouble as I'm not very familiar with JavaScript. Here's what I've got so far. $(function(){ $('.incentives').hide(); $('.incentives-click&a ...

Strategies for effectively engaging with dynamically created forms amidst a multitude of other forms on a webpage

One of the challenges I face is dealing with a page that has multiple forms dynamically generated based on user input. Each form contains two sets of radio buttons, with the second set being disabled by default and enabled based on the users' selectio ...

Creating a bespoke Bootstrap 4 Modal experience without the backdrop

I'm attempting to show a Bootstrap 4 modal without a backdrop. I've tried the following code with no success: .modal.right. modal-backdrop.show { background-color: transparent !important; } When I try this modification, it works (but affect ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

When using QML, functions like Object.keys, Object.values, and JSON.stringify may return unexpected empty results

I have written a code that exposes a C++ object to QML, and I want to verify the declared properties of the object using native JS methods. However, they are not working as expected. I created a method called FizzBuzzDerived.properties, which functions cor ...