Categories
JavaScript Answers

How to Disable Related Videos with the YouTube JavaScript API?

Sometimes, we want to disable related videos with the Youtube JavaScript API. In this article, we’ll look at how to disable related videos with the Youtube JavaScript API.

Disable Related Videos with the Youtube JavaScript API

To disable related videos with the Youtube JavaScript API, we can set the rel property in the playerVars property to 0.

For instance, we can add the following HTML element for the video player:

<div id="player"></div>

Then we can write:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

window.onYouTubeIframeAPIReady = () => {  
  const player = new window.YT.Player("player", {    
    width: 200,    
    height: 100,    
    videoId: "M7lc1UVf-VE",    
    playerVars: {      
      rel: 0,      
      showinfo: 0,      
      ecver: 2   
    }  
  });
};

to add the YouTube script tag with:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Then we set the window.onYouTubeIframeAPIReady to a function that invokes the window.YT.Player constructor with the ID of the element for the player as the first argument.

The 2nd argument is an object with various options like the video width and height and video ID. The playerVars.rel property is set to 0 so that related videos will not be shown.

Conclusion

To disable related videos with the Youtube JavaScript API, we can set the rel property in the playerVars property to 0.

Categories
JavaScript Answers jQuery

How to Determine the Pixel Length of a String in JavaScript?

Sometimes, we want to determine the pixel length of a string in JavaScript.

In this article, we’ll look at how to determine the pixel length of a string in JavaScript.

Determine the Pixel Length of a String in JavaScript

To determine the pixel length of a string in JavaScript, we can put the string in a span and then use the jQuery width method to determine the width of the span.

For instance, we can write the following HTML:

<span></span>

Then we can write:

const span = document.querySelector('span')  
span.innerText = 'Here is my string'  
console.log($(span).width())

to get the span width document.querySelector .

And then we set innerText to the string of the span.

Finally, we log the span’s width that we get from $(span).width() from jQuery.

The console log should log 111.

Conclusion

To determine the pixel length of a string in JavaScript and jQuery, we can put the string in a span and then use the jQuery width method to determine the width of the span.

Categories
Chart.js JavaScript Answers

How to Add Grouped Bar Charts with Chart.js and JavaScript?

Sometimes, we want to add grouped bar charts with Chart.js and JavaScript.

In this article, we’ll look at how to add grouped bar charts with Chart.js and JavaScript.

Add Grouped Bar Charts with Chart.js and JavaScript

To add grouped bar charts with Chart.js and JavaScript, 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.

Conclusion

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

Categories
JavaScript Answers

How to Alert for Unsaved Changes in Form with JavaScript?

Sometimes, we want to alert for unsaved changes in form with JavaScript.

In this article, we’ll look at how to alert for unsaved changes in form with JavaScript.

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.

Conclusion

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.

Categories
JavaScript Answers

How to Paginate a JavaScript Array?

Sometimes, we want to paginate a JavaScript array.

In this article, we’ll look at how to paginate a JavaScript array.

Paginate a JavaScript Array

To paginate a JavaScript array, we can use the slice method to return the chunk of the array we want.

For instance, we can write:

const arr = Array(100).fill().map((_, i) => i)
const paginate = (array, pageSize, pageNumber) => {
  return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
}
console.log(paginate(arr, 10, 1))
console.log(paginate(arr, 10, 2))
console.log(paginate(arr, 10, 3))

We have the arr array with 100 entries.

Then we create paginate function that takes the array , pageSize and pageNumber parameters.

pageNumber starts from 1, so we call slice with (pageNumber — 1) * pageSize as the first argument and pageNumber * pageSize as the 2nd argument to return the slice according to a human-readable page number.

Then from the console log, we see:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

as the returned values of paginate with pageSize 10 and pageNumber 1, 2, and 3 respectively.

Conclusion

To paginate a JavaScript array, we can use the slice method to return the chunk of the array we want.