29

How do i change the background image in CSS at run time? I have the following background image in body and can the image be changed at run time?

body {
height: 100%;
background: #fff8db url(../images/backgrounds/header-top.jpg) no-repeat center top; 
/*background-color: #fff8db;*/
/*background-size: 1650px 900px;*/
font-family: Arial, Verdana, Helvetica, sans-serif; 
font-size:12px; 
font-weight:normal; 
color:#404040;
line-height:20px; }

4 Answers 4

60

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

4
  • 1
    hi THANKS, but i do not get any changes from the code below. <script type="text/javascript"> var body = document.getElementsByTagName('body')[0]; body.style.backgroundImage = 'localhost/ABC/images/backgrounds/header-top1.jpg'; </script>
    – VeecoTech
    Jun 3, 2012 at 3:10
  • You need to either put it at the the end of the body tag or called it when the document loads.
    – user672118
    Jun 3, 2012 at 3:18
  • 4
    Thanks for this solution. Just one question; why not use document.body instead of document.getElementsByTagName('body')[0]? Oct 22, 2014 at 14:21
  • 1
    IIRC document.body is DOM Level 0 and widely supported historically. According to devdocs.io it's not preferred as Firefox may not treat it correctly if the document MIME type is not set to text/html or application/xhtml+xml.
    – vhs
    Oct 4, 2017 at 10:50
22

If you have JQuery loaded already, you can just do this:

$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');

EDIT:

First load JQuery in the head tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:

<script type="text/javascript">
    $(document).ready(function() {
        $('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
    });
</script>
4
  • I tried apply your code in the html, but no changes. <script type="text/javascript"> $('body').css('background-image', 'url(../images/backgrounds/header-top1.jpg)'); </script>
    – VeecoTech
    Jun 3, 2012 at 3:21
  • 12
    Just to point out, the original question asks for a strictly javascript answer and this utilizes jquery. The answer below is the correct way to do this according to the actual question. Not sure why this got picked as best answer. Jul 25, 2013 at 4:01
  • The answer starts with "If you have JQuery loaded already...", which a lot of websites already do. Jan 18, 2014 at 20:45
  • 1
    For pure javascript code, you have to use the background syntax, and not the backgroungImage. e.q. element.style.background = "url('/img/loading/loading.gif') no-repeat center center" Nov 3, 2014 at 17:59
10

Just set an onload function on the body:

<body onload="init()">

Then do something like this in javascript:

function init() {
  var someimage = 'changableBackgroudImage';
  document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}

You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.

2

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.