Home > Enterprise >  Equivalent of $.fn. of jQuery in Vanilla JS
Equivalent of $.fn. of jQuery in Vanilla JS

Time:12-01

Last few days I've been trying to convert this code to pure JS, but no luck until now...

This code basically starts a new Chart.JS instance when called via jQuery object.

(function ($) {
    $.fn.createChartLine = function (labels, datasets, options) {
        var settings = $.extend({}, $.fn.createChartLine.defaults, options);
        this.each(function () {
            
            let ctx = $(this);

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    scales: {
                        y: {
                            title: {
                                display: true,
                                text: settings.labelString
                            },
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: settings.display_legend,
                            position: settings.legend_position,
                            labels: {
                                usePointStyle: settings.legend_pointStyle
                            }
                        }
                    }
                }
            });
        });
    };

    $.fn.createChartLine.defaults = {
        display_legend: true,
        legend_position: 'top',
        legend_pointStyle: true,
        labelString: 'Clicks'
    };
})(jQuery);

The initialization of a new chartline using the code above:

$("#chart1").createChartLine(['1', '2', '3'], [{
        label: 'Clicks',
        backgroundColor: Chart.helpers.color('#007bff').alpha(0.75).rgbString(),
        borderColor: '#007bff',
        data: [34, 56, 28],
        borderWidth: 2,
        tension: 0.4
    }], {display_legend: false});

I tried thousands of ways to remove jQuery from it, but no luck. The intention is to get rid of jQuery in some pages, but this script is essential because with it I can create many Chart.JS instances in same page without needing repeating that amount of code.

I'm aiming to get something like this:

document.getElementById('chart1').createChartLine(...);

Is it possible?

CodePudding user response:

This assumes you are using a version of ChartJS that accepts HTMLCanvasElement and other non-jQuery wrapped Elements to the new Chart() constructor.

You shouldn't extend the prototype of native elements, instead you should create a new function that gets the element(s) passed in.

// Instead of
document.getElementById('chart1').createChartLine(...);

// You'll want
createChartLine(document.getElementById('chart1'), ...);

or something similar.

I'd actually not pass in the element, but rather a selector, since that most closely matches how the jQuery plugin is working.

function createChartLine(selector, labels, datasets, options = {}) {
  const settings = Object.assign(
    {},
    {
      display_legend: true,
      legend_position: "top",
      legend_pointStyle: true,
      labelString: "Clicks",
    },
    options
  );

  const elements = document.querySelectorAll(selector);
  const charts = [];

  for (let i = 0; i < elements.length; i  ) {
    const element = elements[i];
    const newChart = new Chart(element, {
      type: "line",
      data: {
        labels: labels,
        datasets: datasets,
      },
      options: {
        scales: {
          y: {
            title: {
              display: true,
              text: settings.labelString,
            },
            beginAtZero: true,
          },
        },
        plugins: {
          legend: {
            display: settings.display_legend,
            position: settings.legend_position,
            labels: {
              usePointStyle: settings.legend_pointStyle,
            },
          },
        },
      },
    });

    charts.push(newChart);
  }

  return charts;
}

Here is how you'd call the function.

createChartLine(
  "#chart1", // This is the new argument, the selector of the element you are initializing
  ["1", "2", "3"],
  [
    {
      label: "Clicks",
      backgroundColor: Chart.helpers.color("#007bff").alpha(0.75).rgbString(),
      borderColor: "#007bff",
      data: [34, 56, 28],
      borderWidth: 2,
      tension: 0.4,
    },
  ],
  { display_legend: false }
);
  • Related