Reputation: 5236
I want to set background-image
property using JavaScript.
The problem is, I got image links like:
https://cdn.vox-cdn.com/thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn.com/uploads/chorus_image/image/47070706/google2.0.0.jpg
When I try to set this link to style, it can't handle some characters I think.
<div style='background-image: url(urlString);'
Is there any way to handle these characters or do I need to add background-image
using some other way?
Upvotes: 0
Views: 2090
Reputation: 664217
Use quotes around CSS strings in url(…)
:
<div style='background-image: url("https://cdn.vox-cdn.com/thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn.com/uploads/chorus_image/image/47070706/google2.0.0.jpg");'>
Upvotes: 3
Reputation:
element.style.backgroundImage="url('image name')";
should be used. Here element is a variable. If you want to set the background image of the web page then use document.body
instead of element in the code.
Upvotes: 1
Reputation: 484
Use:
element.style.backgroundImage = "url('your cdn path')";
This is a code sippet: https://jsfiddle.net/fnwjhgzw/
Upvotes: 2
Reputation: 2970
var imageURL = 'https://cdn.vox-cdn.com/thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn.com/uploads/chorus_image/image/47070706/google2.0.0.jpg';
var imageElement = document.getElementById('image');
imageElement.style.backgroundImage = "url('"+imageURL+"')";
#image {
height: 300px;
background-position: center;
}
<div id="image">
</div>
Upvotes: 1
Reputation: 16041
You can set it like this:
var div = document.querySelector(...); // select the div
div.style.backgroundImage = "url('" + urlString + "')";
Upvotes: 2