Categories
JavaScript Answers

How to preview an image before and after upload with JavaScript?

Sometimes, we want to preview an image before and after upload with JavaScript.

In this article, we’ll look at how to preview an image before and after upload with JavaScript.

How to preview an image before and after upload with JavaScript?

To preview an image before and after upload with JavaScript, we can read the image file into a URL that we set as the value of the img element’s src attribute with a FileReader instance.

For instance, we write:

<form>
  <input type="file" />
  <img src="">
</form>

to add a form with an input and an img element.

Then we write:

const input = document.querySelector('input')
const img = document.querySelector('img')
const reader = new FileReader();

reader.onload = (e) => {
  img.src = e.target.result;
}

input.onchange = (e) => {
  const [file] = e.target.files
  reader.readAsDataURL(file);
}

We call document.querySelector to select the input and img elements.

Next, we create a new FileReader instance.

And then we set the reader.onload property to a function that gets the image URL from e.target.result and set that as the value of the img.src property.

Next, we set the input.onchange property to a function that gets the selected file from e.target.files.

And then we call reader.readAsDataUrl with file to read the file into a URL string.

Conclusion

To preview an image before and after upload with JavaScript, we can read the image file into a URL that we set as the value of the img element’s src attribute with a FileReader instance.

Categories
JavaScript Answers

How to format hexadecimal number to short UUID in JavaScript?

Sometimes, we want to format hexadecimal number to short UUID in JavaScript.

In this article, we’ll look at how to format hexadecimal number to short UUID in JavaScript.

How to format hexadecimal number to short UUID in JavaScript?

To format hexadecimal number to short UUID in JavaScript, we can use some JavaScript string methods.

For instance, we write:

const toPaddedHexString = (num, len) => {
  const str = num.toString(16);
  return "0".repeat(len - str.length) + str;
}

const hexStr = toPaddedHexString(12345, 16);
const result = hexStr.substr(0, 8) + '-' + hexStr.substr(8, 4) + '-' + hexStr.substr(12, 4);
console.log(result)

We create the toPaddedHexString function to convert num to a hex number.

Then we return the str string padded to len characters with "0".repeat(len - str.length) + str.

Then we call toPaddedHexString with 12345 and 16 to return 12345 converted to hex and padded to 16 characters.

Finally, we add the dashes between the digit groups by calling hex.substr with the start and end indexes of each segment and adding dashes between between them.

Therefore, result is '00000000-0000-3039'.

Conclusion

To format hexadecimal number to short UUID in JavaScript, we can use some JavaScript string methods.

Categories
JavaScript Answers

How to validate a URL in Node.js?

Sometimes, we want to validate a URL in Node.js.

In this article, we’ll look at how to validate a URL in Node.js.

How to validate a URL in Node.js?

To validate a URL in Node.js, we can use the valid-url package.

To install it, we run npm i valid-url.

Then we can use it by writing:

const validUrl = require('valid-url');

const url = "http://bla.com"
if (validUrl.isUri(url)) {
  console.log('Looks like an URI');
}
else {
  console.log('Not a URI');
}

We call the validUrl.isUri method with the url string to check if url is a valid URL string.

Since it’s a URL, isUri should return true.

Therefore, 'Looks like an URI' is logged.

Conclusion

To validate a URL in Node.js, we can use the valid-url package.

Categories
JavaScript Answers

How to remove chars between indexes in a JavaScript string?

Sometimes, we want to remove chars between indexes in a JavaScript string.

In this article, we’ll look at how to remove chars between indexes in a JavaScript string.

How to remove chars between indexes in a JavaScript string?

To remove chars between indexes in a JavaScript string, we can use the JavaScript string substr method.

For instance, we write:

const s = "hi how are you";
const startIndex = 2;
const endIndex = 6;
const newS = s.substr(0, startIndex) + s.substr(endIndex);
console.log(newS)

We want to remove the characters of s between startIndex and endIndex exclusive.

To do this, we call substr with 0 and startIndex to get the part of s between index 0 and startIndex - 1.

And then we call substr again with endIndex to return the part of s between endIndex and the end of the s.

Finally, we concatenate them together and assign it to newS.

Therefore, newS is 'hi are you'.

Conclusion

To remove chars between indexes in a JavaScript string, we can use the JavaScript string substr method.

Categories
JavaScript Answers

How to add gradient instead of solid color fill with JavaScript Chart.js 3?

Sometimes, we want to add gradient instead of solid color fill with JavaScript Chart.js 3.

In this article, we’ll look at how to add gradient instead of solid color fill with JavaScript Chart.js 3.

How to add gradient instead of solid color fill with JavaScript Chart.js 3?

To add gradient instead of solid color fill with JavaScript Chart.js 3, we can set the backgroundColor property of the dataset object to a canvas gradient object.

For instance, we write:

<canvas id="myChart" width="400" height="400"></canvas>

to add the canvas element.

Then we write:

const ctx = document.getElementById('myChart');

const gradient = ctx.getContext('2d').createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(250,174,50,1)');
gradient.addColorStop(1, 'rgba(250,174,50,0)');

const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      fill: true,
      backgroundColor: gradient,
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    },
  }
});

to add a line chart with the area between the x-axis and the line filled in.

We set fill to true to enable the fill.

Then we set backgroundColor to gradient to add the gradient fill.

We call createLinearGradient to create the gradient.

And we call addColorStop to add the gradient colors.

Conclusion

To add gradient instead of solid color fill with JavaScript Chart.js 3, we can set the backgroundColor property of the dataset object to a canvas gradient object.