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 =
"url('http://amigo.com/300107-2853.jpg')";
with perfect result,
yet I fail to do the same with:
document.getElementById("bg_image").style.backgroundImage =
"url('data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...')";
nor
document.getElementById("bg_image").style.backgroundImage =
"data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";
Is there any way to do it?
This is the correct way to make a pure call. No CSS.
What I usually do, is to store the full string into a variable first, like so:
Then, where I want either JS to do something with that variable:
You could reference the same variable via PHP directly using something like:
Works for me ;)
I tried to do the same as you, apparently is the backgroundImage doesn't work with enconded data. As an alternative I suggest to use css classes and the change between those classes.
If you are generating the data "on the fly" you can load the css files dynamically.
CSS:
HTML:
Javascript:
I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/
In my case, it was just because I didn't set the
height
andwidth
.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:
This would work executed from console, but not from within a script:
But after playing with it a bit, I came up with this:
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.:
works too, and even seems to be faster by a few ms than using a proxy image.
Try this, I have got success response ..it's working