12

How to change HTML background with JavaScript Function? I need some simple function to change background from one image to another?

6 Answers 6

5

Try something like this:

function newBackGround (element,background) {
   element.style.backgroundImage = "url("+background+")";
}

newBackground (myElement,"newBackground.jpg");
Sign up to request clarification or add additional context in comments.

Comments

3

An alternative IFF using jquery

$("body").css("background-image", "url(/image.jpg)");

2 Comments

I think it's overkill to import an entire library (jQuery) only for this
That is correct HENCE why I put IFF (if and only if, AND in bold) jquery is being used!!
1

Very simple like this:

function changeBGImage(){
     document.body.background = "image.jpg";
}

UPDATE

Or if you wanna use CSS (more elegant solution) with it, you could use:

<style>
.bg1 {
background-image: url(images/my_image.jpg); 
}
</style>

<body id="page_body">

<script>
function changeBGImage(whichImage){
     document.getElementById('page_body').className="bg"+whichImage;
}
</script>

1 Comment

Well, for one thing "background" isn't a property of the <body> DOM object, at least not in all browsers. The CSS answer should work however and it's really the right way to do it anyway.
1

demo codes:

element = document.querySelector("body");
element.style.backgroundImage =  "url('https://cdn.xgqfrms.xyz/logo/logo.png')";


elements = document.querySelectorAll("div");
for(let element of elements){
  element.style.background =  "url('https://cdn.xgqfrms.xyz/logo/logo.png')";
}

reference links:

http://www.w3schools.com/jsref/dom_obj_style.asp http://www.w3schools.com/jsref/prop_style_background.asp http://www.w3schools.com/jsref/prop_html_style.asp http://www.w3schools.com/jsref/met_document_queryselectorall.asp http://www.w3schools.com/jsref/met_document_queryselector.asp https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll

Comments

0
function changeBGImage(whichImage){
     document.body.style.backgroundImage = "url(" + whichImage + ")";
}

1 Comment

@Pointy, he missed the style property, it should be document.body.style.backgroundImage = "url(" + whichImage + ")";
0

All of these answers change the body. The most direct way to change the html background is like so:

const imagePath = "/img/sub-folder/my-image.png";
document.documentElement.style.background = `url("${imagePath}")`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.