Ad

Change The Background Image Dynamically

- 1 answer

I would like to modify the image in the background with the help of a comment.

The images come from the tmdb API. So I think you have to create a background image component and pass it on to the URL.

I know that CSS has the background-image property, but it works for static images ...

What is the best method, I would like to make this component reusable.

Ad

Answer

Here is how you would have to do it.

  1. Create your <div> and its style with a default background-image
  2. Create 3 <button> to triggers your function changeImage() and provide a parameter
  3. Change the style.backgroundImage with JavaScript such as below:

function changeImage(category){
  document.getElementById('div-bg').style.backgroundImage = 'url("https://source.unsplash.com/320x240/?' + category + '")';
}
#div-bg {
  display: block;
  width: 320px;
  height: 240px;
  background-image: url("https://source.unsplash.com/320x240/?sky");
}
<div id="div-bg"></div>

<button onclick="changeImage('nature')">Nature</button>
<button onclick="changeImage('animal')">Animal</button>
<button onclick="changeImage('fire')">Fire</button>

If you have any question, please ask!

Ad
source: stackoverflow.com
Ad