Reputation: 3
I need to set the background image using PURE javascript (no JQuery or other libraries).
I set the background image using the javascript shown below. The Firefox console, inspector grid, and CSS engine all show that the background image is as it should be. I have successfully set the background color, showing that the element is not hidden, and I am not selecting the wrong element. As the code below shows, I have tried playing with the Opacity and the background color. This was fruitless. Upon hovering the image URL, Firefox shows that the image is in fact loaded correctly.
Here is my javascript:
var shadow = document.getElementById("shadow");
shadow.style.backgroundColor = "transparant";
shadow.style.opacity = "1";
shadow.style.backgroundImage = image;
CSS applied to the element when the program starts
div#shadow
{
opacity: 0;
position: absolute;
top: 315px;
left: 721px;
width: 48px;
height: 48px;
}
The element is just a div nested within the <body>
<html>
<body>
<div id="shadow"></div>
</body>
</html>
Upvotes: 0
Views: 671
Reputation: 65796
You are doing way too much here. No opacity
or transparent
or backgroundColor
is needed. Just set the background
to the image.
But, in CSS whenever you need to supply a path for a property, you need to pass that path using the url()
function, which you don't appear to be doing.
// Best practice: don't set individual properties on the
// style of an element. Add/remove pre-made classes.
document.querySelector("div").classList.add("background");
body { background-color:#e0e0e0; }
div { width:150px; height:150px; border:1px solid black; padding:10px;}
.background {
/* Just set the background property using url(path). That's it. */
background:url("http://www.thetherapystore.com.au/wp-content/uploads/2015/06/SSMILE.jpg");
background-size:contain; /* Only used here to scale the image to fit */
}
<div>This content is in the foreground.</div>
Upvotes: 0
Reputation: 1
Can you provide your "image" var? I replaced you var with a url and it worked fine.
shadow.style.backgroundImage = "url('http://placehold.it/300x300')";
Also, try adding some background properties via CSS, maybe background-size.
Upvotes: 0
Reputation: 491
For the style.backgroundImage
property, you need an image path, like "url('image.png')"
. Otherwise, assign an image URL to the variable image
.
Upvotes: 0
Reputation: 12152
Spelling error in transparent with the url of the image not just the name
var shadow = document.getElementById("shadow");
shadow.style.backgroundColor = "transparent";
shadow.style.opacity = "1";
shadow.style.backgroundImage = "url('image+address')";
div#shadow
{
opacity: 0;
position: absolute;
top: 315px;
left: 721px;
width: 48px;
height: 48px;
}
<html>
<body>
<div id="shadow"></div>
</body>
</html>
Upvotes: 1