I'm writing a simple app with images URLs that contain special characters. I'm not able to set them as CSS background images from javascript code.
I suspect the culprits are the special characters in the URL, but escaping them with '\' doesn't seem to solve the problem.
All images are loaded correctly from the browser, and they work even when set as background property using the CSS editor in the Chrome Developer Tools.
Example code: [JsFiddle Link]
(function() {
document.getElementById("bg-btn").addEventListener("click", function() {
var bg_url = document.getElementById("bg-url").value;
document.getElementsByClassName("container")[0].style.backgroundImage = "url(" + bg_url + ")";
});
})();
.container {
max-width: 300px;
height: 300px;
background: #ccc;
background-size: cover;
}
<div class="container"></div>
URL: <input type="text" id="bg-url">
<button id="bg-btn">Change Background</button>
Working image URL: https://www.spiritdental.com/components/com_easyblog/themes/wireframe/images/placeholder-image.png
Not working image URL: https://img.discogs.com/VF4F5JDIXO8v8A_OLZr4Nh03_so=/fit-in/600x520/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-6029909-1409248351-4058.jpeg.jpg
EDIT:
As many of you suggested adding single quotes in the url('...') expression solve the issue.
But why some URL work even without the single quote? Does the browser assume the argument is a string because it contains safe characters?