You are currently viewing 3 Easy Ways to Change Background Image in JS

3 Easy Ways to Change Background Image in JS

Change Background Image with JavaScript

If you want to set background images for your container element via javascript then this article is for you. When you need dynamic behavior or more complex logic, you can set the background image using javascript because it provides the necessary tools to handle these scenarios effectively. You can set a background image in CSS is generally more straightforward and efficient. So, in this article, we will see how to change the background image with javascript

3 Ways to Set the background image

1. CSS style property:

In this method, we’ll set the background image using the “backgroundImage” property in javascript.
HTML:

<div id="myElement"></div>

CSS:

#myElement {
  width: 80%;
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
}

JS

var element = document.getElementById("myElement");
element.style.backgroundImage = "url('new-image.jpg')";

In this example, you would need an HTML element with the id “myElement” and the JavaScript code would change its background image to “new-image.jpg”.

2, Modifying the class attribute:

Another approach is to define different CSS classes with different background images, and then use JavaScript to change the class assigned to an element. Here’s an example:
HTML:

<div id="myElement" class="default-bg"></div>

CSS:

.default-bg {
  background-image: url('default-image.jpg');
}

.new-bg {
  background-image: url('new-image.jpg');
}

JS:

var element = document.getElementById("myElement");
element.className = "new-bg";

In this example, the JavaScript code changes the class of the element with the id “myElement” From “default-bg” to “new-bg“, which updates the background image accordingly.

3. Dynamically modifying inline styles:

If you want to dynamically change the background image based on user input or other events, you can modify the inline style attribute of an element directly. Here’s an example:
HTML:

<div id="myElement"></div>
<button onclick="changeBackground()">Change Background</button>

JS:

function changeBackground() {
var element = document.getElementById("myElement");
element.style.backgroundImage = "url('new-image.jpg')";
}

In this example, clicking the “Change Background” button triggers the changeBackground() function, which modifies the backgroundImage property of the element, effectively changing the background image.

Leave a Reply