Categories
JavaScript Answers

How to set the background image of a div via a function and function parameter with JavaScript?

Spread the love

Sometimes, we want to set the background image of a div via a function and function parameter with JavaScript.

In this article, we’ll look at how to set the background image of a div via a function and function parameter with JavaScript.

How to set the background image of a div via a function and function parameter with JavaScript?

To set the background image of a div via a function and function parameter with JavaScript, we can create a function that takes the image URL of the background image and returns the CSS background-image property value as a string.

For instance, if we have:

<div>
  hello world
</div>

Then we write:

const getBackgroundImg = (imageUrl) => {
  const urlString = `url(${imageUrl})`
  return urlString
}

const div = document.querySelector('div')
const imageUrl = 'https://image.shutterstock.com/image-photo/nature-background-table-wood-product-260nw-285662423.jpg'

div.style.backgroundImage = getBackgroundImg(imageUrl)

We have the getBackgroundImg function that takes the imageUrl parameter and returns the CSS backgroundImage property value as a string.

Then we select the div with document.querySelector.

And then we define the imageUrl of the background image.

Next, we set div.style.backgroundImage to the background image URL value returned by getBackgroundImg .

Now we should see the background image displayed in the div.

Conclusion

To set the background image of a div via a function and function parameter with JavaScript, we can create a function that takes the image URL of the background image and returns the CSS background-image property value as a string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *