Categories
JavaScript Answers

How to play videos only when visible with HTML5 and JavaScript?

Sometimes, we want to play videos only when visible with HTML5 and JavaScript.

In this article, we’ll look at how to play videos only when visible with HTML5 and JavaScript.

How to play videos only when visible with HTML5 and JavaScript?

To play videos only when visible with HTML5 and JavaScript, we can use the Intersection Observer to check if the video is completely in the screen.

For instance, we write:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4' autoplay="autoplay" controls style='height: 200px'></video>

to add a video element with autoplay enabled.

Then we write:

const video = document.querySelector('video');
let isPaused = false;
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio !== 1 && !video.paused) {
      video.pause();
      isPaused = true;
    } else if (isPaused) {
      video.play();
      isPaused = false
    }
  });
}, {
  threshold: 1
});
observer.observe(video);

to get the video with document.querySelector.

Then we create a new IntersectionObserver instance with a callback that checks if the video is fully in the screen and isn’t paused with entry.intersectionRatio !== 1 && !video.paused.

If both are true, then we pause the video.

Otherwise, we play the video.

Then we call observer.observer to watch when the video is in the screen.

Conclusion

To play videos only when visible with HTML5 and JavaScript, we can use the Intersection Observer to check if the video is completely in the screen.

Categories
JavaScript Answers

How to use a regex to match filename at end of URL with JavaScript?

Sometimes, we want to use a regex to match filename at end of URL with JavaScript.

In this article, we’ll look at how to use a regex to match filename at end of URL with JavaScript.

How to use a regex to match filename at end of URL with JavaScript?

To use a regex to match filename at end of URL with JavaScript, we can use the JavaScript regex exec method.

For instance, we write:

const fileName = /[^/]*$/.exec('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')
console.log(fileName)

We use the /[^/]*$/ regex to match the part of the URL after the last slash.

Then we call exec with a URL to return the match.

As a result, fileName is ['dummy.pdf', index: 62, input: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', groups: undefined]

Conclusion

To use a regex to match filename at end of URL with JavaScript, we can use the JavaScript regex exec method.

Categories
JavaScript Answers

How to generate random integers with probabilities with JavaScript?

Sometimes, we want to generate random integers with probabilities with JavaScript.

In this article, we’ll look at how to generate random integers with probabilities with JavaScript.

How to generate random integers with probabilities with JavaScript?

To generate random integers with probabilities with JavaScript, we can define an array with the possible items that we want to generate with their number of occurrences weighted by their probability.

Then we can use Math.random to pick from the array.

For instance, we write:

const randomWithProbability = () => {
  const notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
  const idx = Math.floor(Math.random() * notRandomNumbers.length);
  return notRandomNumbers[idx];
}
console.log(randomWithProbability())

to define the randomWithProbability function.

In it, we have notRandomNumbers which we draw numbers from.

Then we have

const idx = Math.floor(Math.random() * notRandomNumbers.length);

to return the number index idx of the number we draw.

Conclusion

To generate random integers with probabilities with JavaScript, we can define an array with the possible items that we want to generate with their number of occurrences weighted by their probability.

Categories
JavaScript Answers

How to check file type when file is selected with JavaScript?

Sometimes, we want to check file type when file is selected with JavaScript.

In this article, we’ll look at how to check file type when file is selected with JavaScript.

How to check file type when file is selected with JavaScript?

To check file type when file is selected with JavaScript, we can check the type property of the selected file.

For instance, we write:

<input type="file">

to add a file input.

Then we write:

const input = document.querySelector('input')
const getFileType = (file) => {
  if (file.type.match('image.*'))
    return 'image';
  if (file.type.match('video.*'))
    return 'video';
  if (file.type.match('audio.*'))
    return 'audio';
  return 'other';
}

input.onchange = (e) => {
  const [file] = e.target.files
  console.log(getFileType(file))
}

We select an input with document.querySelector.

Then we define the getfileType function to check the file.type property to check the file type.

Then we set the input.onchange property to a function that get the selected file from e.target.files and call getFileType with it.

Conclusion

To check file type when file is selected with JavaScript, we can check the type property of the selected file.

Categories
JavaScript Answers

How to prepend a zero in front of any number below 10 in JavaScript?

Sometimes, we want to prepend a zero in front of any number below 10 in JavaScript.

In this article, we’ll look at how to prepend a zero in front of any number below 10 in JavaScript.

How to prepend a zero in front of any number below 10 in JavaScript?

To prepend a zero in front of any number below 10 in JavaScript, we can use the JavaScript string’s padStart method.

For instance, we write:

const m = (5).toString().padStart(2, '0')
const n = (100).toString().padStart(2, '0')
console.log(m, n)

to convert 5 to a string with toString and then call padStart to pad the string to length 2 by prepending '0' onto it.

Then we assign the returned string to m.

Likewise, we try to the same thing with 100.

As a result, we see '05' and '100' logged.

Conclusion

To prepend a zero in front of any number below 10 in JavaScript, we can use the JavaScript string’s padStart method.