Categories
JavaScript Answers

How to Remove Whitespaces from the Start and End of a String with JavaScript?

Sometimes, we want to remove whitespaces from the start and end of a string with JavaScript.

In this article, we’ll look at how to remove whitespaces from the start and end of a string with JavaScript.

Remove Whitespaces from the Start and End of a String with JavaScript

To remove whitespaces from the start and end of a string with JavaScript, we can use the replace method to find the line breaks from the start and end of the string.

Then we can replace them all with empty strings.

For instance, we can write:

const str = '    Hello   ';
const trim = str.replace(/^\s+|\s+$/g, '');
console.log(trim);

We have the str string with spaces at the start and end of the string.

Then we call replace with /^\s+|\s+$/ gto match all the whitespaces at the start and end of the string.

^ means start of the string and $ matches the end.

g matches all instances of the spaces.

The 2nd argument is an empty string so we replace all the matches with empty strings.

Therefore, trim is 'Hello’ .

Conclusion

To remove whitespaces from the start and end of a string with JavaScript, we can use the replace method to find the line breaks from the start and end of the string.

Then we can replace them all with empty strings.

Categories
Chart.js JavaScript Answers

How to Handle Click Events on Charts in Chart.js and JavaScript?

Sometimes, we want to handle click events on charts in Chart.js and JavaScript.

In this article, we’ll look at how to handle click events on charts in Chart.js and JavaScript.

Handle Click Events on Charts in Chart.js and JavaScript

To handle click events on charts in Chart.js and JavaScript, we can add the onClick method into our chart.

Then we can use the getElementsAtEventForNode method to get the index of the data set entry that we clicked on.

For instance, we can write the following HTML:

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

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

Then we can add the bar chart by writing:

const 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
}]

const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    onClick(e) {
      const activePoints = myChart.getElementsAtEventForMode(e, 'nearest', {
        intersect: true
      }, false)
      const [{
        index
      }] = activePoints;
      console.log(datasets[0].data[index]);
    }
  }
});

We have the datasets array with the data, border color, and bar colors we want to display.

Also, we have the label to set the label of the legend.

Next, we have the options property set to an object with the onClick method to catch any clicks that were made on the chart.

In it, we call myChart.getElementsAtEventForNode method with the e event object, 'nearest' and an object with intersect set to true to get the nearest object that’s been clicked on.

It returns an array with the index of the dataset data entry that we clicked on.

Then we can get the value of the bar that we clicked on with:

datasets[0].data[index]

Conclusion

To handle click events on charts in Chart.js and JavaScript, we can add the onClick method into our chart.

Then we can use the getElementsAtEventForNode method to get the index of the data set entry that we clicked on.

Categories
JavaScript Answers

How to Clear a Drop Down List with JavaScript ?

Sometimes, we want to clear a drop-down list with JavaScript.

In this article, we’ll look at how to clear a drop-down list with JavaScript.

Clear a Drop Down List with JavaScript

To clear a drop-down list with JavaScript, we can use the empty or html method.

For instance, if we have the following dropdown and submit button:

<select>
  <option value='0' disabled selected>Select Value</option>
  <option value='1'>Value 1</option>
  <option value='2'>Value 2</option>
</select>

<input type="submit" value="click me" />

Then we can clear the dropdown with we click on the submit button with jQuery by writing:

$('input').on('click', () => {
  $('select').empty();
});

We add a click handler to the input element with on .

Then in the click handler, we call empty on the select dropdown to empty its entries.

We can do the same thing by calling html on the select dropdown with an empty string:

$('input').on('click', () => {
  $('select').html("");
});

The select dropdown will also be emptied once the button is clicked.

Conclusion

To clear a drop-down list with JavaScript, we can use the empty or html method.

Categories
JavaScript Answers

How to Create a JavaScript setInterval Callback Function that Clears Itself?

Sometimes, we want to create a JavaScript setInterval callback function that clears itself.

In this article, we’ll look at how to create a JavaScript setInterval callback function that clears itself.

Create a JavaScript setInterval Callback Function that Clears Itself

To create a JavaScript setInterval callback function that clears itself, we can call the clearInterval function with the timer handle as the argument.

For instance, we can write:

const myInterval = setInterval(() => {  
  console.log('hello')  
  clearInterval(myInterval);  
}, 50);

to call setInterval with a callback that logs 'hello' and then calls clearIntrval with the timer handle returned by setInterval to clear the timer.

The 2nd argument is set to 50 so that the callback runs every 50 milliseconds.

But the callback will only run once since we called clearInterval with myInterval to stop the timer.

Conclusion

To create a JavaScript setInterval callback function that clears itself, we can call the clearInterval function with the timer handle as the argument.

Categories
JavaScript Answers

How to Sort Divs in JavaScript Based on data-sort Attribute Values?

Sometimes, we want to sort divs in JavaScript based on data-sort attribute values.

In this article, we’ll look at how to sort divs in JavaScript based on data-sort attribute values.

Sort Divs in JavaScript Based on data-sort Attribute Value

To sort divs in JavaScript based on data-sort attribute values, we can use the JavaScript array sort method to sort the elements based on the data-sort attribute value.

For instance, if we have the following HTML:

<section>
  <div data-sort='12'>div12</div>
  <div data-sort='4'>div4</div>
  <div data-sort='19'>div19</div>
  <div data-sort='1'>div1</div>
  <div data-sort='8'>div8</div>
</section>

Then we can display the divs in the order of their data-sort attribute values by writing:

const result = [...$('div')].sort((a, b) => {
  const contentA = parseInt($(a).data('sort'));
  const contentB = parseInt($(b).data('sort'));
  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});

$('section').html(result);

We select the divs with $ and convert the nodelist to an array with the spread operator.

Then we call sort on the array with a callback that gets the data-sort attribute value of element a and b with:

$(a).data('sort')

and

$(b).data('sort')

Then we call parseInt to parse the values into integers.

Then we return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0; to sort the elements in ascending order of their data-sort attribute values.

And finally, we put the sorted divs into the section element with:

$('section').html(result);

Now we should see:

div1
div4
div8
div12
div19

displayed.

Conclusion

To sort divs in JavaScript based on data-sort attribute values, we can use the JavaScript array sort method to sort the elements based on the data-sort attribute value.