0

This is my CSS

    <style>
body {
background: url(30.gif) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>

This makes the background image fit to screen.

Now, if I attempt to make the background image dynamic using JS as follows, the background image no longer fits to screen.

<style>
body {
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>

And JS

body.style.background = 'url(30.gif) no-repeat center center fixed';

This makes the image appear to the original size. I want the image to be fit to screen.

I tried the following but to no avail:

body.style.background = 'url(30.gif) no-repeat center center fixed width:100% height:100%';

How do I correct the error?

Cody Raspien
  • 1,753
  • 5
  • 26
  • 51

1 Answers1

2

Your JS is overwriting your CSS. You need to include background-size in your JS, like this (assuming you've stored document.body in a variable named body as indicated):

body.style.background = 'url(30.gif) center center/cover fixed no-repeat';

Alternatively, try setting all properties separately in CSS, and make sure the body always fills the viewport, like this:

body {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -ms-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  background-attachment: fixed;
  background-position: 50% 50%;
  background-repeat: no-repeat:
  min-height: 100vh;
}

Then if you need to set the background-image dynamically, do it like so:

body.style.backgroundImage = 'url(30.gif)';

You may need to do it like this because setting the background shorthand property will override individual properties, breaking your vendor-prefixed background-sizing.

AM Douglas
  • 1,873
  • 1
  • 13
  • 17
  • Thank you. This works on desktop but not mobile (only image height is very small and there is a lot of blank space below it). Any clue? – Cody Raspien Oct 30 '16 at 16:17
  • I tried adding the following line after setting the URL - body.style.background.size = "100% 100%"; On mobile, doesn't work. – Cody Raspien Oct 30 '16 at 16:20
  • Updated my answer – AM Douglas Oct 30 '16 at 16:27
  • My original solution may not have worked either because the body element isn't tall enough to fill a mobile screen in portrait, or because the background shorthand overwrote a vendor-prefixed background-size. – AM Douglas Oct 30 '16 at 16:38