I want to set background-image
property using JavaScript.
The problem is, I got image links like:
=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn/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?
I want to set background-image
property using JavaScript.
The problem is, I got image links like:
https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./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?
- 2 What does this have to do with JS? Looks like you're using an inline style attribute in HTML. – Bergi Commented Feb 27, 2018 at 14:54
- Your title clearly says you want to do thsi from JavaScript, but the content of your question only shows HTML and an inline style. Do you need to do this in an inline style, or through JavaScript, or via a stylesheet? – T.J. Crowder Commented Feb 27, 2018 at 15:07
5 Answers
Reset to default 3Use quotes around CSS strings in url(…)
:
<div style='background-image: url("https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./uploads/chorus_image/image/47070706/google2.0.0.jpg");'>
You can set it like this:
var div = document.querySelector(...); // select the div
div.style.backgroundImage = "url('" + urlString + "')";
Use:
element.style.backgroundImage = "url('your cdn path')";
This is a code sippet: https://jsfiddle/fnwjhgzw/
var imageURL = 'https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./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>
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.