0

Basically, What I'm trying to do is load images such that the entire image takes up the background of the browser frame, which I've been able to do statically no problem. I'm trying to implement it so that I can dynamically load different images generated randomly.

If I do it using document.body.style.backgroundImage="url('img/" + image.image + "')"; I can see the image that it loads just fine. But sometimes there will be whitespace near the bottom boarder of the image.

Ideally, I want to set it within a div, however, this also wont load, and I'm left with a white background: document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')"; I also tried: document.getElementById("pic").style.background = "url('img/" + image.image + "')";

If I specify a static image in the css for my 'pic' class, it works perfectly. ex. background: url("http://lorempixel.com/1600/1200/nature/") ;

Here's the CSS:

body {  
  top:0px;
  left:0px;
  height:100%;
  width:100%;  
  z-index:-1;
  opacity:1;
  background-repeat: no-repeat;
  background-size: cover;
}
.pic {
  position:fixed;
  top:0px;
  left:0px;
  width:100%;
  height:100%;
  z-index:-1;
  opacity:1;
  background-repeat: no-repeat;
  background-size: cover;
}

Using either the body, or the div element would be fine with me, so long as I can dynamically load images in the frame without whitespaces or repeats. Also, I don't understand why I can't get the background of the div to load dynamically at all, if someone could explain what I'm doing incorrectly there.Any help would be appreciated.

1
  • Can you please show your whole code at jsFiddle? Commented Jul 20, 2014 at 3:21

1 Answer 1

1

It seems that you are setting the class 'pic' on div tag but you are getting the element div with it's id('pic').

Either, change the attribute 'class' to 'id' for 'pic' vlaue on div element,

Like use

<div id="pic">

instead of

<div class="pic">

OR, use getElementsByClassName() method, like

document.getElementsByClassName("pic")[0].style.backgroundImage = "url('img/" + image.image + "')";

instead of

document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')";
Sign up to request clarification or add additional context in comments.

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.