Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

321
Views
Base64 background-image not displaying

I am trying to set a div's background to a base64 image dynamically. The base64 image itself is stored in a string variable, base64Image. I am using the following line of code.

$("#loadingAdImage").css("background-image", `url("${base64Image}")`);

When I inspect the the div element, I find that even though the line was executed, the div has no style attribute. I even tried the following.

$("#loadingAdImage").attr("style", `background-image: url('${base64Image}')`);

This time when I inspected the div element, I got the style attribute, but the image itself isn't displaying in the background. Does anyone know what's wrong?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This should work, it shows the images as loaded :-

HTML

<div id="test">

JS

var pic = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfMAAAHyCAMAAADIj";
// the pic data should be a lot bigger, change it to whatever data you have //
var img = new Image();
img.src = pic;
$("#test").css("background-image", "url('" + img.src + "')");
about 4 years ago · Juan Pablo Isaza Report

0

Use an img tag for #loadingAdImage

then use this code

    $("#loadingAdImage").attr("src", "data:image/png;base64, "+base64Image);
about 4 years ago · Juan Pablo Isaza Report

0

The only way I can think of where this would happen is for base64Image to contain a " character.

Any other value would set the property correctly given your code:

const sources = [
 "foo bar'¨^*-0+:.?/#`😱", // many "special" characters but no double quote
 "foo \"bar" // contains a double quote
];
const test = (index) => {
  const source = sources[index];
  console.log(
    { source,
      result: $("#test" + index).css("background-image", `url("${source}")`)
        .attr("style")
    }
  );
};
test(0);
test(1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test0"></div>
<div id="test1"></div>

So double check your base64Image value, and remove any " in there, it's not part of the base64 encoding characters and it has nothing to do in a base64 encoded data: URL.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!