Categories
JavaScript Answers

How to remove an HTML element using JavaScript?

To remove an HTML element using JavaScript, we call the remove method.

For instance, we write

element.remove();

to call the element.remove method to remove element from the DOM.

Categories
JavaScript Answers

How to set date in input type date with JavaScript?

To set date in input type date with JavaScript, we set the valueAsDate property.

For instance, we write

document.getElementById("datePicker").valueAsDate = new Date();

to select the date input with getElementById.

And then we set its valueAsDate property to the date value.

Categories
JavaScript Answers

How to add image to canvas with JavaScript?

To add image to canvas with JavaScript, we call the drawImage method.

For instance, we write

const canvas = document.getElementById("viewport");
const context = canvas.getContext("2d");
const baseImage = new Image();
baseImage.src = "img/base.png";
baseImage.onload = () => {
  context.drawImage(baseImage, 0, 0);
};

to select the canvas with getElementById.

And we get its context with getContext.

Next we create an img element with the Image constructor.

And then we call drawImage with baseImage when the image is loaded.

We load the image by setting the src property to the image URL string.

Categories
JavaScript Answers

How to record audio to file with HTML5 and JavaScript?

To record audio to file with HTML5 and JavaScript, we call the getUserMedia method.

For instance, we write

const audio = document.getElementById("audio_preview");
const onRecordFail = (e) => {
  console.log(e);
};

navigator.getUserMedia(
  { video: false, audio: true },
  (stream) => {
    audio.src = window.URL.createObjectURL(stream);
  },
  onRecordFail
);

to select the audio element with getElementById.

Then we call navigator.getUserMedia with { video: false, audio: true } to let us record audio.

We call it with a callback that gets the captured data from stream and create a base64 URL from it with createObjectURL.

We set it as the src property value to play in the audio element.

onRecordFail is called when capturing fails.

Categories
JavaScript Answers

How to create a new line in JavaScript?

To create a new line in JavaScript, we call document.write.

For instance, we write

document.write("<br>");

to add a br line break element.

Or we write

document.write("\n");

to add a new line