Categories
JavaScript Answers

How to Add an Image Preview When an Image File is Selected in the File Input?

Adding a preview for the selected image is something that we’ve to do sometimes in our JavaScript web app.

In this article, we’ll look at how to add an image preview to show the image the user is selected.

Add an Image Preview for a File Input

To add the image preview for a file input, first, we add the file input and the img element to display the image preview:

<form>
  <input type='file' />
  <img src="#" alt="selected image" />
</form>

We set the type to file to make the input a file input.

Next, we need to add some JavaScript code to read the file into a base64 string.

Then we can set the src property of the img element to the base64 string.

To do this, we write:

const imgInput = document.querySelector('input')
const imgEl = document.querySelector('img')

imgInput.addEventListener('change', () => {
  if (imgInput.files && imgInput.files[0]) {
    const reader = new FileReader();
    reader.onload = (e) => {
      imgEl.src = e.target.result;
    }
    reader.readAsDataURL(imgInput.files[0]);
  }
})

We get the input and img elements with document.querySelector .

Then we call addEventListener on the imgInput with a callback to let us watch for file selection.

We pass in 'change' to watch the change event, which is triggered when we select a file.

In the callback, we check is imgInput.files is present.

files has the selected files.

We get the first file with the 0 index.

Then we create the FileReader instance to read the selected file.

And we set the onload method which runs when a file is selected.

We get the e.target.result to get the file result.

The file should be read into a base64 string, which is a valid value for the src attribute of an img element.

Therefore, we can set img.src property directly to e.target.result .

And to trigger the reading of the file, we call reader.readAsDataURL method with imgInput.files[0] , which has the first selected file.

The createObjectURL Method

We can also use the createObjectURL method to create the base64 string from the selected image file.

For instance, we can write:

const imgInput = document.querySelector('input')
const imgEl = document.querySelector('img')

imgInput.addEventListener('change', () => {
  if (imgInput.files && imgInput.files[0]) {
    imgEl.src = URL.createObjectURL(imgInput.files[0]);
    imgEl.onload = () => {
      URL.revokeObjectURL(imgEl.src)
    }
  }
})

and keep the HTML code the same.

We call URL.createObjectURL with imgInput.files[0] to create the base64 string from the file object stored in imgInput.files[0] .

Then we set the onload method of the img element object, which is run when the src attribute of the img element changes.

We call URL.revokeObjectURL there to free the image object from memory.

Conclusion

We add an image preview to our JavaScript app by reading the selected image file into a base64 string and setting it as the value of the src attribute of an img element.

Categories
JavaScript Answers

How to Add a New Array Elements at the Beginning of an Array in JavaScript?

Adding a new array element to the beginning of an array is something that we’ve to sometimes in our JavaScript apps.

In this article, we’ll look at how to add new array elements at the beginning of an array in JavaScript.

Array.prototype.concat

One way to add an element to the beginning of a JavaScript array is to use the concat method.

We call concat with a new array with the element we want to add.

Then we pass in the existing array as the argument.

For instance, we can write:

const array = [1, 2, 3]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array)
console.log(newArray);

We have the array array that we want to add a new first element to.

newFirstElement is the first element we want to add.

To do this, we create a new array with newFirstElement in it.

Then we call concat with array to concatenate array to the new array we created.

A new array with both of them combined is returned, so newArray is [4, 1, 2, 3] .

Array.prototype.unshift

The unshift method available with JavaScript arrays is specially made to add an element to the beginning of an array.

The addition of the element is done in place, so the array it’s called on is mutated.

For instance, we can write:

const array = [1, 2, 3]
array.unshift(4);
console.log(array);

Then array is [4, 1, 2, 3] .

Spread Operator

We can use the spread operator to add elements from one array to another by making a copy and putting the items in the new array.

For instance, if we have:

const array = [1, 2, 3]
const newArray = [4, ...array];
console.log(newArray);

Then all the items from array are spread into the newArray .

Therefore, newArray is [4, 1, 2, 3] .

Array.prototype.splice

Another way to add an element to the beginning of an array is to use the splice method.

splice changes an array it’s called in place.

For instance, we can write:

const array = [1, 2, 3]
array.splice(0, 0, 4);
console.log(array);

We call splice with the index of array we want to change in the first argument.

The 2nd argument is the number of elements we want to remove starting from the index we specified in the first argument.

And the last argument is the element we want to insert before the index we have in the first argument.

Therefore, array should be [4, 1, 2, 3] .

Conclusion

We can use array methods or the spread operator to add items to the beginning of an array with JavaScript.

Categories
JavaScript Answers

How to Convert a String to an Integer in JavaScript?

Converting a string to an integer in JavaScript is something that we may have to do sometimes.

In this article, we’ll look at how to convert a string to an integer with JavaScript.

The Number Function

We can use tyhe Number function to convert an integer string into an integer.

For instance, we can write:

const num = Number("1000")  
console.log(num)

Then num is 1000.

The parseInt Function

The parseInt function also lets us convert an integer string into an integer.

It takes the number string and the base of the number we’re converting respectively.

For instance, we can write:

const num = parseInt("1000", 10);  
console.log(num)

Then we get the same result as the previous example.

Unary Plus Operator

The unary plus operator also converts a string to an integer.

So we can put the + operator right before the integer to convert it to a number.

For instance, we can write:

const num = +"1000"  
console.log(num)

and get the same result.

Math.floor

The Math.floor method rounds a number down to the nearest integer.

It also accepts a number string, so we can pass it into the Math.floor method, and it’ll return the integer rounded down to the nearest integer.

For instance, we can write:

const num = Math.floor("1000.05")  
console.log(num)

And we get that num is 1000.

Math.round

The Math.round method also lets us round a number.

The rule for rounding is that if the fractional portion of the argument is bigger than 0.5, then the argument is rounded to the next highest integer in absolute value.

Otherwise, it’ll be rounded to the nearest integer with the lower absolute value.

It also takes a string and will do the conversion to a number before rounding.

For instance, we can write:

const num = Math.round("1000.05")  
console.log(num)

The parseFloat Function

The parseFloat function lets us convert a floating point number string into a number.

It also works with converting integer strings into integers.

For instance, we can write:

const num = parseFloat("1000")  
console.log(num)

Conclusion

There are many ways to convert an integer string to an integer with JavaScript.

Categories
JavaScript Answers

How to Get the Selected Value from a Dropdown List using JavaScript?

Getting the selected value of a dropdown is something that we’ve to sometimes in JavaScript.

In this article, we’ll look at how to get the selected value from a dropdown with JavaScript.

Get the Selected Value from a Dropdown List

To get the selected value from a dropdown list, we can get the select element.

Then we can use the value property to get the value of the value attribute of the selected option element.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
  <option value="3">grape</option>
</select>

Then the 2nd option element is selected since we have the selected attribute added to it.

So we can write:

const select = document.querySelector("select");
const selectedChoice = select.value;
console.log(selectedChoice)

to get the select element with document.querySelector .

Then we get the value of the value attribute of the select option element with the value property.

And then we should see that selectedChoice is 2.

Get the Text of the Selected Option Element from a Dropdown List

We can also get the text of the select option element from a dropdown list.

To do that, we write:

const select = document.querySelector("select");
const value = select.options[select.selectedIndex].value;
const text = select.options[select.selectedIndex].text;
console.log(value, text)

assuming we have the same HTML code as before.

We get the select element with document.querySelector .

Then we get all the options in an object with the select.options property.

select.selectedIndex has the index of the selected option element.

The value property has value of the value attribute of the selected element.

And text property has the text of the option element in the selected element.

Therefore, value is 2 and text is 'orange' .

Watch for Changes

We can listen to the change event of the dropdown to watch for changes in the choice of the selected item.

For example, if we have the same select element of the previous 2 examples, we can write:

const select = document.querySelector("select");
select.addEventListener('change', (event) => {
  const {
    value,
    text
  } = event.target.options[event.target.selectedIndex]
  console.log(value, text)
})

We get the select element as we did before.

Then we get the options from the event.target.options .

And we can access the index of the selected choice with the event.target.selectedIndex .

Then we can get the value of the value property with the value property.

And text gets the text content of the selected item in the option element.

Conclusion

We can get the selected option element from the select element with the value property, which has the value of the value attribute of the selected option element.

We can also get all the options with the options property.

selectedIndex gets the index of the selected option element.

Categories
JavaScript Answers

How to Check if a JavaScript Variable Exists?

JavaScript variables may be declared without setting a value for them.

They can also be set to undefined .

In this article, we’ll look at how to check if a JavaScript variable is initialized or whether it’s undefined .

The typeof Operator

One way to check if a JavaScript variable exists is to use the typeof operator.

For instance, we can write:

let x;  
console.log(typeof x === 'undefined')

If x isn’t initialized, then it’s the same as setting it to undefined .

So typeof x returns 'undefined' .

Therefore, the console.log returns true .

Falsy Check

We can also check if a variable is falsy to see if it’s a falsy value, which includes undefined , null , '' (empty string), 0, NaN , or false .

Truthy value is any value other than those values.

For instance, we can write:

let x;  
console.log(Boolean(x))

Then console log logs false since x is uninitialized, so it’s undefined .

And since Boolean converts any falsy value to false , that’s what we get.

Equivalently, we can use !! to do the same thing:

let x;  
console.log(!!(x))

Conclusion

We can use the typeof operator or the Boolean function to check if a variable is initialized or not.