Categories
JavaScript Answers

How to playback HTML audio with fade in and fade out with JavaScript?

Sometimes, we want to playback HTML audio with fade in and fade out with JavaScript.

In this article, we’ll look at how to playback HTML audio with fade in and fade out with JavaScript.

How to playback HTML audio with fade in and fade out with JavaScript?

To playback HTML audio with fade in and fade out with JavaScript, we can adjust the volume of the audio as it’s being played.

For instance, we write:

<audio id='audio' controls>
  <source src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg">
</audio>

to add the audio element.

Then we write:

const sound = document.getElementById('audio');
const fadeAudio = setInterval(() => {
  const fadePoint = sound.duration - 5;
  if ((sound.currentTime >= fadePoint) && (sound.volume !== 0)) {
    sound.volume -= 0.1
  }

  if (sound.volume < 0.003) {
    clearInterval(fadeAudio);
  }
}, 200);

We get the audio element with document.getElementById.

Then we call setInterval with a callback that gets the fadePoint of the sound, which is the time near the end of the clip.

Then we check if sound.currentTime is bigger than or equal to fadePoint and sound.volume isn’t 0.

sound.currentTime is the current time of the sound clip.

If both are true, then we reduce the volume by 0.1

And if sound.volume is less than 0.003, then we call clearInterval to stop reducing sound volume.

We run the callback every 200 seconds reduce the sound volume slowly to create the fading effect.

Conclusion

To playback HTML audio with fade in and fade out with JavaScript, we can adjust the volume of the audio as it’s being played.

Categories
JavaScript Answers

How to create a string that contains all ASCII characters with JavaScript?

Sometimes, we want to create a string that contains all ASCII characters with JavaScript.

In this article, we’ll look at how to create a string that contains all ASCII characters with JavaScript.

How to create a string that contains all ASCII characters with JavaScript?

To create a string that contains all ASCII characters with JavaScript, we can use the String.fromCharCode method to get the characters with codes from 32 to 126 and combine them together.

For instance, we write:

let s = '';

for (let i = 32; i <= 126; i++) {
  s += String.fromCharCode(i);
}

console.log(s)

We create a for loop that looped from 32 to 126, assign them to i, and call String.fromCharCode with i.

Then we concatenate the returned character to s.

Therefore, s is '!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.

Conclusion

To create a string that contains all ASCII characters with JavaScript, we can use the String.fromCharCode method to get the characters with codes from 32 to 126 and combine them together.

Categories
JavaScript Answers

How to create a random token in JavaScript?

Sometimes, we want to create a random token in JavaScript.

In this article, we’ll look at how to create a random token in JavaScript.

How to create a random token in JavaScript?

To create a random token in JavaScript, we can use the Math.random method with the toString method.

For instance, we write:

const rand = () => {
  return Math.random().toString(36).substr(2);
};

const token = () => {
  return rand() + rand();
};

console.log(token());

We create a random number with Math.random.

Then we call toString with 36 to convert the number to a base 36 number string.

And then we call `substr with 2 to remove the initial 0’s.

We then call rand twice and combine the strings together and return it.

Conclusion

To create a random token in JavaScript, we can use the Math.random method with the toString method.

Categories
JavaScript Answers

How to convert a blob to a base64 string with JavaScript?

To convert a blob to a base64 string with JavaScript, we can use the FileReader instance’s readAsDataURL method.

For instance, we write:

const imageUrl = "https://picsum.photos/200/300";

const reader = new FileReader();
reader.onloadend = () => {
  const base64data = reader.result;                
  console.log(base64data);
}

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  reader.readAsDataURL(imageBlob);  
})()

We create the FileReader instance and set the onloadend property to a function that gets the base64 string from reader.result.

Next, we call fetch with the imageUrl to make a GET request to the image URL.

Then we call response.blob to return a promise with the image blob object.

Finally, we call readAsDataURL with imageBlob to read it into a base64 string.

Categories
JavaScript Answers

How to convert a date string (YYYYMMDD) to a date with JavaScript?

Sometimes, we want to convert a date string (YYYYMMDD) to a date with JavaScript.

In this article, we’ll look at how to convert a date string (YYYYMMDD) to a date with JavaScript.

How to convert a date string (YYYYMMDD) to a date with JavaScript?

To convert a date string (YYYYMMDD) to a date with JavaScript, we can call the JavaScript string’s substring method to extract the year, month, and day from the string.

Then we can use the Date constructor to convert it to a JavaScript date.

For instance, we write:

const dateString = "20200515";
const year = +dateString.substring(0, 4);
const month = +dateString.substring(4, 6);
const day = +dateString.substring(6, 8);

const date = new Date(year, month - 1, day);
console.log(date)

to call substring to extract the year, month and day substrings from the dateString.

Then we use the unary + operator to convert the strings to numbers.

Next, we use the Date constructor with year, month - 1 and day to create the date from the substrings.

We’ve to subtract month by 1 since JavaScript month starts with 0 for January.

Therefore, date is:

Fri May 15 2020 00:00:00 GMT-0700 (Pacific Daylight Time)

Conclusion

To convert a date string (YYYYMMDD) to a date with JavaScript, we can call the JavaScript string’s substring method to extract the year, month, and day from the string.

Then we can use the Date constructor to convert it to a JavaScript date.