Categories
JavaScript Answers

How to Check if a Background Image is Loaded with JavaScript?

Sometimes, we want to check if a background image is loaded with JavaScript.

In this article, we’ll look at how to check if a background image is loaded on a page with JavaScript.

Listen to the load Event

We can listen to the load event of a background image to see if it’s loaded.

If it’s loaded, then we can set the background image to the image with the same URL as the background image.

For instance, we can write:

const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
const bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
`
preloaderImg.addEventListener('load', (event) => {
  bgElement.style.backgroundImage = `url(${imageUrl})`;
  preloaderImg = null;
});

We have the imageUrl with the image we want to load as the background image.

Then we get the body element with document.querySelector .

And then we create the preloaderImg element with document.createElement with the image we want to preload.

Next, we set the preloaderImg.src to imageUrl .

Then we call addEventListener on preloaderImg with 'load' as the first argument to watch for the preloaderImg loading.

The callback will run when it’s loaded.

And so we can set the bgElement.style.backgroundImage to set the background image to the image that’s loaded in the preloaderImg element.

And then we set preloaderImg to null to clear the preloaded image.

Now we should see the background image loaded in our page.

Conclusion

We can listen to the load event of an image element to see if an image is loaded.

Then once it’s loaded, we can use the image URL of the preloaded image to set the background image of the page.

Categories
JavaScript Answers

How to Get HTML5 Local Storage Keys with JavaScript?

Sometimes, we want to get the keys of the items that we stored in our browser’s local storage in our web app.

In this article, we’ll look at how to get the keys of the items stored in local storage with JavaScript.

Use the Object.entries Method

We can use the Object.entries method to get the keys and values of the items stored in local storage.

For instance, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const entries = Object.entries(localStorage)
console.log(entries)

Then entries is:

[
  [
    "foo",
    "1"
  ],
  [
    "bar",
    "2"
  ]
]

since Object.entries returns an array of key-value pair arrays in the localStorage object.

We use localStorage.setItem with the key and value of the item we want to store as arguments respectively.

Use the Object.keys Method

Also, we can use the Object.keys method to get the keys of the items that are stored in local storage.

For instance, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = Object.keys(localStorage)
console.log(keys)

Then keys is [“foo”, “bar”] .

Use the localStorage.key Method

Another way to get all the keys of the items stored in local storage is to use the localStorage.key method.

We can use it along with the localStorage.length property to create an array to populate the keys with.

localStorage.length has the number of items stored in local storage.

To use them, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = [...Array(localStorage.length)].map((o, i) => {
  return localStorage.key(i);
})
console.log(keys)

We spread the empty array with length localStorage.length , spread that into a new array, then call map with a callback to return the key that we get by calling localStorage.key with the i index.

As a result, keys is also [“foo”, “bar”] .

Conclusion

There’re several ways we can use the get the items stored in local storage with JavaScript.

Categories
JavaScript Answers

How to Use Lodash to Find and Return an Object from a JavaScript Array?

Sometimes, we want to use Lodash to find and return an object from a JavaScript array.

In this article, we’ll look at how to use Lodash to find and return an object from a JavaScript array.

Using the find Method

We can use the find method to find an object with a predicate function that returns the condition of the object we’re looking for.

For instance, we can write:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, (o) => {
  return o.description === 'object3';
});
console.log(obj)

We pass in the array to search as the first argument.

And we pass in the predicate function that returns the condition of the object we’re looking for as the 2nd argument.

Therefore, obj is:

{description: "object3", id: 3}

We can also pass in an object as the 2nd argument to search for an object with the property with the given value:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, {
  description: 'object3'
});
console.log(obj)

And we can pass in an array with the property key and value to do the same search:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, ['description', 'object3']);
console.log(obj)

They all get the same result as the first example.

Conclusion

We can use the Lodash find method to find the object with the given condition in an array.

Categories
JavaScript Answers

How to Retrieve the Text of the Selected option Element in a select Element with JavaScript?

Sometimes, we want to retrieve the text of the selected option element in a select element with JavaScript.

In this article, we’ll look at how to retrieve the text of the selected option element in a select element with JavaScript.

Use the selectedIndex Property

We can get the index of the selected item with the selectedIndex property.

Then we can use the text property to get the text of the selected item.

For instance, if we have the following HTML:

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

Then we can write the following JavaScript code to get the selected item from the select element:

const getSelectedText = (el) => {
  if (el.selectedIndex === -1) {
    return null;
  }
  return el.options[el.selectedIndex].text;
}

const select = document.querySelector('select')
const text = getSelectedText(select);
console.log(text)

We create the getSelectedText function that takes an element as the parameter.

Then we check if selectedIndex is -1.

If it’s -1, then nothing is selected and we return null .

Otherwise, we get the options with el.options .

And then we get the selected option by passing in the el.selectedIndex into the square brackets.

Finally, we get the text property to get the text of the selected option element.

Therefore, the console log should log 'orange' .

Conclusion

We can retrieve the text of a selected option element with the selectedIndex and text properties.

Categories
JavaScript Answers

How to Convert a Unix Timestamp to a Calendar Date with Moment.js?

Sometimes, we want to convert a Unix timestamp to a calendar date with Moment.js.

In this article, we’ll look at how to convert a Unix timestamp to a calendar dare with moment.js.

Use the unix and format Methods

We can use the unix method to create a moment object from a timestamp.

Then we can use the format method to format the date into a calendar date.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment.unix(dt / 1000).format("MM/DD/YYYY");  
console.log(dateString)

We create the dt date object with the Date constructor.

Then we convert it to a timestamp in milliseconds with the unary + operator.

Next, we call moment.unix with a timestamp in seconds.

And then we call format to format the date into MM/DD/YYYY format.

And so dateString is ‘02/01/2021’ .

Use the moment Function and the format Method

We can just use the moment function without the unix method to create a moment object from a timestamp.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment(dt).format("MM/DD/YYYY");  
console.log(dateString)

The moment function takes a timestamp in milliseconds.

Therefore, we don’t have to divide dt by 1000 when we pass it in.

The rest of the code is the same and we get the same result as before.

Conclusion

We can convert a timestamp to a calendar date with format with the moment function or the unix method with the format method.