Check Out the Chart.js Course: Chart.js, The Missing Manual Course
Categorias
Uncategorized

Should You Use Onclick or addEventListener in JavaScript?

Both onclick and addEventListener are used to attach JavaScript event handlers to elements, but they have some differences in terms of flexibility, maintainability, and compatibility. Here’s a comparison to help you decide when to use each:

onclick:

Simplicity

  • onclick is simpler and more concise. It directly assigns a function to the onclick property of an element.
<button onclick="myFunction()">Click me</button>

HTML Attributes:

  • It allows you to define event handlers directly in the HTML attributes, which can be convenient for small scripts or quick prototyping.

Scope Issues:

  • The function specified in onclick has access to the global scope. This can lead to scope-related issues, especially in larger applications.

addEventListener:

Flexibility:

  • addEventListener provides more flexibility. You can attach multiple event listeners to the same element or handle multiple types of events for the same listener.
const button = document.getElementById('myButton');
button.addEventListener('click', myFunction);

Clearer Separation:

  • It promotes a clearer separation of HTML, CSS, and JavaScript. JavaScript code is kept separate from HTML attributes, making the codebase more maintainable.

Dynamic Event Handling:

  • addEventListener allows you to add or remove event listeners dynamically during the runtime, providing more control over the application’s behavior.

Scope Control:

  • The function specified in addEventListener is executed in the context of the target element, helping to avoid global scope pollution.

When to Use Each:

For Simple Cases:

  • If you have a simple case with just one event handler and a small script, onclick can be convenient.

For Larger Applications:

  • For larger applications, where separation of concerns, maintainability, and dynamic event handling are crucial, addEventListener is preferred.

Consistency:

  • If you are working on a project that uses a consistent coding style and best practices, using addEventListener might be more aligned with modern JavaScript development practices.

Compatibility

  • If you need to support older browsers, keep in mind that addEventListener is more widely supported than onclick when it comes to handling multiple event listeners.

In summary:

In modern JavaScript development, and especially for larger and more maintainable codebases, addEventListener is often preferred due to its flexibility and separation of concerns. However, for simpler cases, or in situations where conciseness is a priority, onclick can still be suitable.

Categorias
Uncategorized

When to Use Button or A HREF in Javascript?

In JavaScript, the choice between using a <button> element and an <a> (anchor) element depends on the intended functionality and the specific use case. Here are some guidelines for when to use each:

Use <button> when:

Form Submission:

  • If the element triggers a form submission, such as submitting a form or triggering a form reset, <button> is the more appropriate choice. You can use the type attribute with values like “submit” or “reset” to define the button’s behavior.
<button type="submit">Submit</button>

JavaScript Actions:

  • When the button is designed to trigger a JavaScript function or action, using <button> is common. You can use the onclick attribute or add an event listener in JavaScript to handle the button click.
<button onclick="myFunction()">Click me</button>

Styling and Interaction:

  • If you want to create a button with specific styling and interactions (e.g., hover effects), <button> provides more flexibility. You can easily style buttons using CSS.
<button class="styled-button">Click me</button>

Use <a> when:

Navigation:

  • If the element is intended to navigate to another page or resource, the <a> element is the appropriate choice. You can use the href attribute to specify the destination.
<a href="/pt/page/">Go to Page</a>

Linking to External Resources:

  • If the link is meant to navigate within the same page, for example, linking to a specific section or anchor on the page, <a> with a fragment identifier is appropriate.
<a href="#section">Go to Section</a>

Styling and Interaction:

  • While buttons provide more control over styling, sometimes using <a> with appropriate CSS can create visually appealing links that resemble buttons.
<a href="#" class="styled-link">Click me</a>

In summary

In summary, use <button> for actions within the current page or to trigger JavaScript functions, and use <a> for navigation, linking to external resources, or creating links within the same page. The choice also depends on the semantic meaning and the user experience you want to achieve.

Categorias
Uncategorized

How to show all data points on radar chart using Chart.js 4

To add extra datapoints we will be using a custom plugin.

This code defines a Chart.js plugin called subLabels that is used to draw additional circular sub-labels around a radar chart. Let’s break down the code:

Plugin Definition:

const subLabels = {
  id: 'subLabels',
  beforeDatasetsDraw(chart, args, plugins) {
    // Code for drawing sub-labels
  }
};

  • The plugin is defined as an object with an id property set to ‘subLabels’ and a method beforeDatasetsDraw.
  • The beforeDatasetsDraw method is a hook that is called before the datasets are drawn on the chart.

Drawing Sub-Labels:

const { ctx, data, scales: {r} } = chart;
const xCenter = r.xCenter;
const yCenter = r.yCenter;
const drawingArea = r.drawingArea;
const segmentDrawingArea = r.drawingArea / 6;
const angle = Math.PI / 180;

  • The code extracts the chart context (ctx), data, and the radial scale (r) from the chart object.
  • Variables like xCenter, yCenter, drawingArea, segmentDrawingArea, and angle are defined for convenience.

Loop for Drawing Circular Sub-Labels:

const tickLength = r.ticks.length - 1;
const labelLength = data.labels.length - 1;

for(let i = 1; i < tickLength; i++) {
  for(let j = 0; j <= labelLength; j++) {
    // Drawing code for each circular sub-label
  }
}

  • The code initializes variables tickLength and labelLength based on the number of ticks and labels in the radar chart.
  • Two nested loops iterate over the ticks and labels to draw circular sub-labels.

Drawing Each Circular Sub-Label:

ctx.save();
ctx.translate(xCenter, yCenter);
ctx.rotate(angle * 72 * j);
ctx.beginPath();
ctx.fillStyle = data.labels[j];
ctx.arc(0, -segmentDrawingArea * i, 10, angle * 0, angle * 360, false);
ctx.fill();

ctx.fillStyle = 'white';
ctx.font = 'bold 12px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(i, 0, -segmentDrawingArea * i);
ctx.restore();

  • Inside the nested loops, the code saves the current canvas state, translates to the radar chart center, and rotates the canvas based on the angle.
  • It then draws a filled circular sub-label with a color from data.labels.
  • The label text (i) is drawn in white above the circular sub-label.

End of Drawing Logic:

  1. The entire drawing logic is enclosed within the beforeDatasetsDraw method, which ensures that these circular sub-labels are drawn before the main datasets of the radar chart.

In summary, this Chart.js plugin adds circular sub-labels around a radar chart to provide additional information or visual cues.

See full code below:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Getting Started with Chart JS with www.chartjs3.com</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100vw;
        height: 40px;
        background: #1A1A1A;
        color: rgba(54, 162, 235, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;
      }
      .chartCard {
        width: 100vw;
        height: calc(100vh - 40px);
        background: rgba(54, 162, 235, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(54, 162, 235, 1);
        background: white;
      }
    </style>
  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM (Chart JS <span id="chartVersion"></span>)</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">
        <canvas id="myChart"></canvas>
      </div>
    </div>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
    <script>
    // setup 
    const data = {
      labels: ['Red', 'Orange', 'Green', 'Blue', 'Brown'],
      // datasets: [{
      //   label: 'Growth Chart',
      //   data: [1, 2, 3 ,4 ,5],
      //   backgroundColor: [
      //     'rgba(0, 0, 0, 0.2)'
      //   ],
      //   borderColor: [
      //     'rgba(0, 0, 0, 1)'
      //   ],
      //   borderWidth: 1,
      // }]
    };

    const subLabels = {
      id: 'subLabels',
      beforeDatasetsDraw(chart, args, plugins) {
        const { ctx, data, scales: {r} } = chart;

        console.log(r)
        const xCenter = r.xCenter;
        const yCenter = r.yCenter;
        const drawingArea = r.drawingArea;
        const segmentDrawingArea = r.drawingArea / 6;
        const angle = Math.PI / 180;

        
        const tickLength = r.ticks.length - 1;
        const labelLength = data.labels.length - 1;

        for(let i = 1; i < tickLength; i++) {
          for(let j = 0; j <= labelLength; j++) {
          ctx.save();
          ctx.translate(xCenter, yCenter);
          ctx.rotate(angle * 72 * j)
          ctx.beginPath();
          ctx.fillStyle = data.labels[j];
          ctx.arc(0, -segmentDrawingArea * i, 10, angle * 0, angle * 360, false);
          ctx.fill();

          ctx.fillStyle = 'white';
          ctx.font = 'bold 12px sans-serif';
          ctx.textAlign = 'center';
          ctx.fillText(i, 0, -segmentDrawingArea * i)
          ctx.restore();
          }
        }
      }
    }

    // config 
    const config = {
      type: 'radar',
      data,
      options: {
        scales: {
          r: {
            min: 0,
            max: 6,
            ticks: {
              callback: ((value, index, ticks) => {
                return '';
              })
            }
          } 
        }
      },
      plugins: [subLabels]
    };

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );

    // Instantly assign Chart.js version
    const chartVersion = document.getElementById('chartVersion');
    chartVersion.innerText = Chart.version;
    </script>

  </body>
</html>
Categorias
Uncategorized

How to draw a dashed line on a scatter plot in Chart JS 4

To do this we will need to use showLine to force a line being drawn and add a borderDash with an array value. Where we specific how many pixels are solid and how many pixels are transparent.

  1. showLine: true:
    • This property is used to determine whether to draw a line between data points or not.
    • When set to true, a line will be drawn connecting the data points in the chart.
    • In your context, since you’re using a scatter plot with the type: 'line', setting showLine: true makes sure that a line is drawn connecting the data points, essentially converting your scatter plot into a line chart.
  2. borderDash: [6, 6]:
    • This property is used to create a dashed line effect in the border of the dataset.
    • It takes an array of values, where each pair of values represents the length of the dash and the length of the gap between dashes.
    • In your example, [6, 6] means that the line will consist of dashes with a length of 6 units, followed by gaps of 6 units. This creates a visually distinct dashed pattern in the line.

In summary, these properties are used to control the appearance of the line in your line chart.

The showLine: true ensures that a line is drawn, and borderDash: [6, 6] specifies that the line should be dashed with a dash length of 6 units and a gap length of 6 units.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Getting Started with Chart JS with www.chartjs3.com</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100vw;
        height: 40px;
        background: #1A1A1A;
        color: rgba(54, 162, 235, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;
      }
      .chartCard {
        width: 100vw;
        height: calc(100vh - 40px);
        background: rgba(54, 162, 235, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(54, 162, 235, 1);
        background: white;
      }
    </style>
  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM (Chart JS <span id="chartVersion"></span>)</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">
        <canvas id="myChart"></canvas>
      </div>
    </div>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
    <script>
    // setup 
    const data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      datasets: [{
        label: 'Weekly Sales',
        data: [18, 12, 6, 9, 12, 3, 9],
        backgroundColor: [
          'rgba(255, 26, 104, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(0, 0, 0, 0.2)'
        ],
        borderColor: [
          'rgba(255, 26, 104, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(0, 0, 0, 1)'
        ],
        borderWidth: 1,
        showLine: true,
        borderDash: [6, 6]
      }]
    };

    // config 
    const config = {
      type: 'line',
      data,
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    };

    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );

    // Instantly assign Chart.js version
    const chartVersion = document.getElementById('chartVersion');
    chartVersion.innerText = Chart.version;
    </script>

  </body>
</html>
Categorias
Uncategorized

How to Hide Border Lines From Scales in Chart JS 4

Let’s explore how to hide the border lines from the x and y scales.

How to Hide Border Lines From Scales in Chart JS 4

Step 1: Get Chart.js 4

First, make sure you have Chart.js 4 in your project. You can either download it or include it from a website (like a library). Just make sure it’s there in your project.

Get the boiler template at: Getting Started with Chart JS

Step 2: Make a Simple Chart

Now, create a basic chart using Chart.js. Think of it like setting up a canvas where your chart will be drawn. You decide what kind of chart it is (like a line chart) and what data it shows.

Step 3: Hide Border Lines

Now, if you want to make your chart look cleaner by removing the lines on the sides (like borders), you can do that. We’ll hide the lines on the bottom (x-axis) and the side (y-axis).

const options = {
  scales: {
    x: {
      display: true,
      grid: {
        display: false, // Hide x-axis lines
        drawOnChartArea: false // removes the grid
        drawTicks: false // removes the tick marks
      },
      border: {
        display: false // remove border lines
      }
    },
    y: {
      display: true,
      grid: {
        display: false, // Hide y-axis lines
        drawOnChartArea: false // removes the grid
        drawTicks: false // removes the tick marks
      },
      border: {
        display: false // remove border lines
      }
    },
  },
};

Here, we’re remove all the possible lines that exist from scale. In total there are 3 lines on both the x and y scales:

  1. grid lines
  2. tick marks
  3. border lines

Conclusion

Customizing your charts can make them look better for your website or app. Hiding those lines on the sides is one way to do it. Just follow these steps, and you’ll have a clean and nice-looking chart on your web page!

Categorias
Uncategorized

Introduction to Chart js Annotation Plugin

  1. Introduction to Chart js annotation
    • A. Explanation of Chart.js
    • B. Explanation of annotation in Chart.js
    • C. Importance of annotation in visualizing data
    • D. Overview of what will be covered in the blog post
  2. Getting started with Chart.js annotation
    • A. Setting up Chart.js
    • B. Adding annotation to your chart
    • C. Understanding annotation configuration options
    • D. Examples of basic annotation
  3. Advanced annotation techniques
    • A. Adding custom labels and images to annotation
    • B. Annotation positioning and styling options
    • C. Using annotations to highlight specific data points
    • D. Interactive annotations with Chart.js plugins
  4. Best practices for using annotation in Chart.js
    • A. Keep annotations simple and informative
    • B. Avoid cluttering the chart with too many annotations
    • C. Use annotations sparingly to avoid overwhelming the user
    • D. Testing and iterating on your annotations to ensure effectiveness
  5. Real-world examples of annotation in Chart.js
    • A. Sales data visualization with annotation
    • B. Stock market analysis with annotation
    • C. Sports data visualization with annotation
  6. Conclusion
    • A. Recap of the importance of annotation in Chart.js
    • B. Summary of key takeaways from the blog post
    • C. Encouragement to experiment with annotation in your own Chart.js charts.

Introduction to Chart js Annotation Plugin

If you’re looking to create stunning data visualizations with Chart.js, you may want to consider adding annotations to your charts. Annotations are an essential tool for communicating data insights and can help make your charts more informative and engaging. In this blog post, we’ll explore the ins and outs of annotations in Chart.js and provide you with the knowledge and tools you need to create powerful visualizations that effectively communicate your data.

We’ll begin by explaining what Chart.js is and what annotations are, then delve into the importance of annotations in visualizing data. We’ll cover the basics of getting started with Chart.js annotations, including how to set up Chart.js and add annotations to your chart. From there, we’ll explore advanced annotation techniques such as custom labels, images, and interactive annotations.

We’ll also provide you with some best practices for using annotations in Chart.js, such as keeping annotations simple and informative, avoiding clutter, and testing and iterating on your annotations. Finally, we’ll showcase some real-world examples of how annotations can be used in Chart.js, including sales data visualization, stock market analysis, and sports data visualization.

By the end of this blog post, you’ll have a comprehensive understanding of Chart.js annotations and be ready to experiment with adding annotations to your own visualizations. So, let’s dive in!

Getting started with Chart.js annotation

A. Setting up Chart.js

Before diving into annotation, it’s important to have a basic understanding of Chart.js. Chart.js is an open-source JavaScript library used for creating interactive charts and graphs on the web. It’s built on top of HTML5 canvas and offers a wide range of chart types including line, bar, pie, and more. To get started with Chart.js, you can download the library from their official website or use a CDN.

B. Adding annotation to your chart

Annotation is a powerful tool in Chart.js that allows you to add custom labels and images to your chart. To add an annotation to your chart, you need to create an object that defines the type of annotation, its position, and its content. For example, to add a label annotation to a line chart, you can use the following code:

options: {
  annotation: {
    annotations: [{
      type: 'line',
      mode: 'vertical',
      scaleID: 'x-axis-0',
      value: 'March',
      borderColor: 'red',
      borderWidth: 2,
      label: {
        enabled: true,
        content: 'Annotation Label'
      }
    }]
  }
}

This will add a vertical line annotation at the ‘March’ data point with a red border and a label that says ‘Annotation Label’.

C. Understanding annotation configuration options

Chart.js offers a variety of configuration options for annotations, such as type, mode, scaleID, value, borderColor, borderWidth, and more. Understanding these options is crucial to creating effective annotations. The Chart.js documentation provides a comprehensive list of all the available options and their descriptions.

D. Examples of basic annotation

To get started with annotation, it’s helpful to see some examples. The Chart.js documentation offers several basic annotation examples, including adding a horizontal line, vertical line, box, and label annotations to a line chart.

In the next section, we’ll explore some advanced annotation techniques to take your Chart.js charts to the next level.

Advanced Annotation Techniques

After getting started with Chart.js annotation, you might want to take your annotations to the next level by using more advanced techniques. In this section, we will cover some of the more advanced annotation techniques that you can use to create more informative and visually appealing charts.

A. Adding Custom Labels and Images to Annotation

While Chart.js provides several built-in annotation types, you can also create custom labels and images to add to your annotations. This allows you to add more context and information to your charts, making them more informative and visually appealing.

To add a custom label or image to your annotation, you need to use the Label and Image annotation types. You can then customize the appearance and positioning of your label or image using the available configuration options.

B. Annotation Positioning and Styling Options

Another way to enhance your annotations is by customizing their positioning and styling. Chart.js provides several options for positioning and styling your annotations, allowing you to create annotations that blend seamlessly into your chart.

For example, you can position your annotations using the x and y coordinates, or you can use the mode option to position them relative to the chart area or a specific data point. You can also customize the appearance of your annotations by changing the font size, font color, background color, and border color.

C. Using Annotations to Highlight Specific Data Points

One of the most useful advanced annotation techniques is using annotations to highlight specific data points in your chart. You can do this by adding annotations that point to or surround specific data points, making them stand out from the rest of the chart.

For example, you can add a label or image annotation that points to a data point, or you can use the BoxAnnotation type to highlight a range of data points. This technique is especially useful when you want to draw attention to important or unusual data points in your chart.

D. Interactive Annotations with Chart.js Plugins

Finally, you can take your annotations to the next level by using Chart.js plugins to create interactive annotations. Plugins allow you to add more advanced functionality to your annotations, such as tooltips, click events, and animations.

There are several plugins available for Chart.js that can be used to create interactive annotations, such as the chartjs-plugin-annotation and chartjs-plugin-datalabels plugins. By using these plugins, you can create annotations that respond to user interaction, making your charts more engaging and interactive.

By using these advanced annotation techniques, you can create more informative and visually appealing charts that effectively communicate your data. However, it’s important to keep in mind that too many annotations can clutter your chart and make it difficult to read. So, it’s always best to use annotations sparingly and test and iterate on your annotations to ensure their effectiveness.

Best practices for using annotation in Chart.js

When using annotation in Chart.js, it’s important to keep in mind best practices to ensure your visualizations are effective and not overwhelming. Here are some key best practices to follow:

A. Keep annotations simple and informative

Annotations should provide relevant information to the user without being too complicated or difficult to understand. Keep the text concise and use simple language that’s easy to read.

B. Avoid cluttering the chart with too many annotations

Too many annotations can make your chart cluttered and difficult to read. Use annotations sparingly and only include the most important information.

C. Use annotations sparingly to avoid overwhelming the user

While annotations can be helpful in providing context to your data, too many annotations can be overwhelming for the user. Be selective in the annotations you choose to include and prioritize the most important information.

D. Testing and iterating on your annotations to ensure effectiveness

It’s important to test your annotations and iterate on them to ensure they’re effective in providing the necessary context and information to your users. Consider soliciting feedback from your audience to make improvements.

By following these best practices, you can ensure that your annotations enhance the user’s understanding of your data visualization rather than detract from it.

Real-world examples of annotation in Chart.js

Data visualization is an important aspect of many industries, including sales, finance, and sports. Here are some real-world examples of how Chart.js annotation can be used to enhance data visualization in these industries.

A. Sales data visualization with annotation

In the sales industry, it is essential to track key metrics such as revenue, profit, and customer acquisition. Chart.js annotation can be used to highlight important events, such as product launches, marketing campaigns, or promotions. Annotations can be used to mark the start and end dates of these events, making it easier to track their impact on sales metrics.

B. Stock market analysis with annotation

In finance, stock market analysis involves tracking a variety of metrics, including stock prices, volume, and trading activity. Chart.js annotation can be used to highlight key events such as earnings reports, dividends, or major news events that impact the market. Annotations can also be used to mark important technical indicators, such as moving averages or support and resistance levels, which can help traders make more informed decisions.

C. Sports data visualization with annotation

In the sports industry, data visualization is used to track player performance, team statistics, and game outcomes. Chart.js annotation can be used to highlight important events, such as game-winning goals, record-breaking performances, or injuries. Annotations can also be used to provide additional context to visualizations, such as player or team comparisons, that can help fans and analysts better understand the data.

By incorporating annotation into their Chart.js visualizations, professionals in a variety of industries can improve the clarity and impact of their data. Whether tracking sales metrics, analyzing the stock market, or tracking sports statistics, Chart.js annotation provides a powerful tool for enhancing data visualization.

Conclusion

In conclusion, Chart.js annotation is a powerful tool for visualizing and presenting data in a meaningful way. By adding annotations to your charts, you can provide context, highlight important data points, and make your charts more engaging and informative.

Throughout this blog post, we covered the basics of setting up and using annotation in Chart.js, as well as advanced techniques for customizing and enhancing your annotations. We also discussed best practices for using annotations effectively and shared real-world examples of annotation in sales data visualization, stock market analysis, and sports data visualization.

As you experiment with annotation in your own Chart.js charts, remember to keep your annotations simple and informative, avoid cluttering the chart with too many annotations, use annotations sparingly to avoid overwhelming the user, and test and iterate on your annotations to ensure effectiveness.

With these tips and techniques, you can take your Chart.js charts to the next level and create more meaningful and impactful visualizations. So go ahead and start experimenting with annotation in your own charts today!

Categorias
Uncategorized

Chartjs Plugin Sorting

The Chart.js sorting plugin is a plugin that allows you to quickly sort the bar chart ASC (low to high), DESC (high to low) and reset the values back to initial load. 

The idea came based on a comment of a viewer who was wondering why Chart.js sorting option has been so complicated and this simple feature should be built in. After contemplating it, realizing it would be quite doable this plugin was made. 

Chartjs Plugin Sorting or better the Sorting Plugin for Chart.js makes sorting a breeze. Removing the option to code you own. 

Getting Started

How to install? To install this you will need to add the JavaScript file of the sorting plugin into your HTML file. Make sure you add this after the Chart.js Library file. 

Once you did that you need to activate the file. It has been added but it is still on standby. To activate the file we need to register the Chart.js plugin. Understanding that it is now ready to start. 

To do this we use the command with the plugin name, which is ‘ChartjsPluginSorting’.  

// Register ChartjsPluginSorting
Chart.register(ChartjsPluginSorting)

Once registered, and loaded correctly you will see the three buttons immediately and the bar chart can be sorted. All the buttons are nested within a DIV container. 

The three Buttons

The Sorting Plugin for Chart.js has three buttons. All buttons are built in HTML. Which means that adding css styling to these buttons is easy by assigning a class to each specific button. 

There buttons are: 

  • ASC or Low to High Button
  • DESC or High to Low Button
  • Reset Button

ASC or Low to High Button

The ASC or Low to High Button will sort the values from low to high. If there are multiple identical values it will sort them according to lowest values and alphabetical order based on the x scale labels of the category scale type. 

How to customize the ASC Button:

NameTypeScriptableIndexableDefaultVideo Explainer
classstringNoNo
labelstringNoNo‘Asc’
topPositionnumberNoNo0
rightPositionnumberNoNo40

DESC or High to Low Button

The DESC or High to Low Button will sort the values from high to low. If there are multiple identical values it will sort them according to highest values and the reversed alphabetical order based on the x scale labels of the category scale type. 

How to customize the DESC Button:

NameTypeScriptableIndexableDefaultVideo Explainer
classstringNoNo
labelstringNoNo‘Desc’
topPositionnumberNoNo0
rightPositionnumberNoNo0

Reset Button

The reset button is self explanatory and will reset the values back to initial load.

How to customize the Reset Button. 

NameTypeScriptableIndexableDefaultVideo Explainer
classstringNoNo
labelstringNoNo‘Reset’
topPositionnumberNoNo0
rightPositionnumberNoNo80
Categorias
Uncategorized

Ternary Operator JavaScript

Ternary Operator JavaScript

The ternary operator is a shorthand way to write a conditional statement in JavaScript. It is also known as the ternary conditional operator.

Ternary Operator JavaScript

Here is the syntax for the ternary operator:

condition ? expression1 : expression2

The condition is evaluated first. If it is true, expression1 is executed. If the condition is false, expression2 is executed.

The video below will show you how to use the ternary operator in JavaScript.

Ternary Operator JavaScript

Code Ternary Operator JavaScript

Here is an example of using the ternary operator javascript snippet:

<script>
  let x = 30;
  let y = 50;
  let max = (x > y) ? x : y;
  console.log(max)
</script>
Categorias
Uncategorized

How to Create Radio Button Checked CSS Styling

How to Create Radio Button Checked CSS Styling

How to Create Radio Button Checked CSS Styling

In this video we will explore how to create radio button checked with css styling. This is basic video helping people who start out with HTML to learn how to create radio button grouped together and change the design of the checked button.

A radio button group is a group of radio buttons that are connected. Only one option can be selected with a radio button. By grouping them it understands which radio button is part of the group. However, adding styling to CSS requires some tricky options. We will use the :after and :checked attribute to make a custom design.

How to Create Radio Button Checked CSS Styling

Code Radio Button Checked CSS Styling

Below you can find the code snippet of the Radio Button Checked CSS Styling.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Create Radio Button Checked CSS Styling</title>
    <style>
      input[type="radio"]:after {
        width: 15px;
        height: 15px;
        border-radius: 15px;
        top: -1px;
        left: -1px;
        position: relative;
        background-color: gray;
        content: '';
        display: inline-block;
        visibility: visible;
        border: 0px solid white;
      }
      input[type="radio"]:checked:after {
        background-color: green;
      }

      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100vw;
        height: 40px;
        background: #1A1A1A;
        color: rgba(255, 26, 104, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;
      }
      .chartCard {
        width: 100vw;
        height: calc(100vh - 40px);
        background: rgba(255, 26, 104, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(255, 26, 104, 1);
        background: white;
        height: 200px;
      }
    </style>
  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM | How to Create Radio Button Checked CSS Styling</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">

        <form action="">
          <label>
            <input type="radio" name="radio-group" value="yes"> Yes
          </label>
          <br>
          <label>
            <input type="radio" name="radio-group" value="no"> No
          </label>
        <input type="hidden" name="trp-form-language" value="pt"/></form>

      </div>
    </div>
  </body>
</html>
Categorias
Uncategorized

How to Create HTML Radio Button by Default Checked

How to Create HTML Radio Button by Default Checked

How to Create HTML Radio Button by Default Checked

In this video we will explore how to create html radio button by default checked. This is basic video helping people who start out with HTML to learn how to create radio button grouped together and set a value checked by default.

A radio button group is a group of radio buttons that are connected. Only one option can be selected with a radio button. By grouping them it understands which radio button is part of the group. And forcing a selected option by default.

How to Create HTML Radio Button by Default Checked

Code of HTML Radio Button Default Checked

Below you can find the code snippet of the HTML Radio Button by Default Checked.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Create HTML Radio Button by Default Checked</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: sans-serif;
      }
      .chartMenu {
        width: 100vw;
        height: 40px;
        background: #1A1A1A;
        color: rgba(255, 26, 104, 1);
      }
      .chartMenu p {
        padding: 10px;
        font-size: 20px;
      }
      .chartCard {
        width: 100vw;
        height: calc(100vh - 40px);
        background: rgba(255, 26, 104, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .chartBox {
        width: 700px;
        padding: 20px;
        border-radius: 20px;
        border: solid 3px rgba(255, 26, 104, 1);
        background: white;
        height: 200px;
      }
    </style>
  </head>
  <body>
    <div class="chartMenu">
      <p>WWW.CHARTJS3.COM | How to Create HTML Radio Button by Default Checked</p>
    </div>
    <div class="chartCard">
      <div class="chartBox">

        <form action="">
          <label>
            <input type="radio" name="radio-group" value="1"> Yes
          </label>
          <br>
          <label>
            <input type="radio" name="radio-group" value="0" checked> No
          </label>
        <input type="hidden" name="trp-form-language" value="pt"/></form>

      </div>
    </div>
  </body>
</html>
pt_PTPortuguese (Portugal)