I want to change background dynamically in JS and my set of images is in base64 encoded. I try:
document.getElementById(\"bg_image\").style.backgroundImage =
In my case, it was just because I didn't set the height
and width
.
But there is another issue.
The background image could be removed using
element.style.backgroundImage=""
but couldn't be set using
element.style.backgroundImage="some base64 data"
Jquery works fine.
Had the same problem with base64. For anyone in the future with the same problem:
url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";
This would work executed from console, but not from within a script:
$img.css("background-image", "url('" + url + "')");
But after playing with it a bit, I came up with this:
var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");
No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.
Hope it helps someone.
EDIT
Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).
Simply using e.g.:
$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");
works too, and even seems to be faster by a few ms than using a proxy image.
I tried this (and worked for me):
var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';
ES6 syntax:
let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = ´url('${img}')´
A bit better:
let setBackground = src=>{
this.style.backgroundImage = `url('${src}')`
}
let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF
setBackground.call(node, img)