Categories
Chart.js JavaScript Answers

How to Add Grouped Bar Charts with Chart.js?

To add grouped bar charts with Chart.js, we just have to put all the chart data in the datasets array property.

For instance, we can add the Chart.js script and the canvas for the chart with the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

to get the canvas 2d context with:

const ctx = document.getElementById('myChart').getContext('2d');

Then chart data is defined with:

const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [{
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4]
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5]
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6]
    }
  ]
};

Each entry has the data for each bar.

They’ll be grouped together into a group bar chart with Chart.js.

Then we create our chart with:

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
        }
      }]
    }
  }
});

We just set type to 'bar' to create a grouped bar chart.

Categories
Chart.js JavaScript Answers

How to Hide Decimal Points on Numbers on the Y-Axis in Chart.js?

To hide decimal points on numbers on the y-axis in Chart.js, we can set the stepSize option.

For instance, we can write the following HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

to add the Chart.js script and the canvas for the chart.

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 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)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 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)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        ticks: {
          stepSize: 1,
          beginAtZero: true,
        },
      },
    },
  }
});

to create the chart.

We set the options.scales.y.ticks.stepSize property to 1 so the numbers on the y-axis will always be integers with no trailing decimal.

Categories
JavaScript Answers jQuery

How to Toggle Showing and Hiding a Div When Clicking a Button with jQuery?

To toggle showing and hiding a div when clicking a button with jQuery, we can use the jQuery toggle method to toggle a div on and off.

For instance, if we have the following HTML:

<input type='button' id='hideshow' value='hide/show'>  
<div id='content'>Hello World</div>

Then we toggle to show and hide a div when we click on the input button by writing:

$(document).ready(() => {  
  $('#hideshow').on('click', (event) => {  
    $('#content').toggle('show');  
  });  
});

We call $(‘#hideshow’).on with 'click' to add a click event handler for the button.

Then in the event handler, we call toggle with 'show' to toggle the div on and off.

Categories
JavaScript Answers

How to Alert for Unsaved Changes in Form with JavaScript?

To alert for unsaved changes in form with JavaScript, we can track changes done to inputs in a form.

Then we can set the window.onbeforeunload property to a function that checks the changing state of the input and returns an alert message if there’re changes.

For instance, if we have:

<div id="app">
  <input />
</div>

Then we can write the following JavaScript to track whether the input value has changed and shows the alert when the user leaves the page when there’re changes made:

let unsaved = false;

const input = document.querySelector("input");
input.addEventListener("change", () => {
  unsaved = true;
});

const unloadPage = () => {
  if (unsaved) {
    return "You have unsaved changes on this page.";
  }
};

window.onbeforeunload = unloadPage;

We have the unsaved variable, which we set to true in the change event listener of the input that we added with input.addEventListener .

And then we have the unloadPage function that checks if unsaved is true .

If it is, then we return a string that triggers the alert when we set the function as the value of window.onbeforeunload .

The message can’t be changed, so we can return any string.

onbeforeunload runs when we leave the page.

Categories
JavaScript Answers

How to Add Event Listeners to Multiple Elements in a Single Line with JavaScript?

To add event listeners to multiple elements in a single line with JavaScript, we can call addEventListener on document .

Then in the event handler, we can check which element is clicked.

For instance, we can write the following HTML:

<button>  
  button 1  
</button>  
<button>  
  button 2  
</button>  
<button>  
  button 3  
</button>  
<div>  
  not button  
</div>

Then we can check if a button is clicked in the click event handler by writing:

document.addEventListener('click', (e) => {  
  if (e.target.tagName == "BUTTON") {  
    console.log('button clicked');  
  }  
})

We use e.target.tagName to get the tag name of the element that’s clicked.

Then we know a button is clicked if tagName is 'BUTTON' .

This works because JavaScript events propagate to ancestor elements by default.