How to change background image using javascript

Using javascript we can change our HTML elements easily. In this post, we will learn how can we change background images using javascript.


We will learn three types of background changing techniques.

  • βœ… Change background image automatically.
  • βœ… Change background image after clicking on the button.
  • βœ… Change background image randomly.

Change background image using javascript.

Change the background image is actually changing the CSS or apply the CSS to our elements. So if you know how to apply or change the CSS of an HTML element using javascript, you can change the background image easily.
So to apply or change the CSS of an HTML element first we need to select the element then change or apply the CSS using the style property of our element.

Let’s change the background image using javascript

myDiv.style.backgroundImage = "url('your-image-path')";
Here, inside the url method you need to put your image path.
Download the complete soruce code.

Changes background image automatically.

changeBackgroundImageAutomatically();
function changeBackgroundImageAutomatically(){
 // main code  goes here
}
Here we just call our functions changeBackgroundImageAutomatically() without any event trigger.
Download the complete soruce code.

Change background image after a button Click.

bgChageBtn.addEventListener('click',function(){
	chageBackgroundAfterClick();
})
function chageBackgroundAfterClick(){
 // main code  goes here
}
Here we call our chageBackgroundAfterClick() function after clicking the button.
Download the complete soruce code.

Change background image randomly for every load.

Suppose we have three images and we want to change our background image randomly from our collection (3 images). In this case, you can use the javascript random function.

chageBackgroundImageRandomly();

function chageBackgroundImageRandomly(){
	// 3 image
	let allImage = [
		'path-1',
		'path-2',
		'path-3'
	];
	let randomIndex = Math.floor(Math.random() * allImage.length);
	// 0, 1 or 2
	
    myDiv.style.backgroundImage = "url('"+allImage[randomIndex]+"')";
}
Here we use the javascript random function to generate a random index Between 0 and our array length.
Download the complete soruce code.
Still you face problems, feel free to contact with me, I will try my best to help you.