fonefix
fonefix

Reputation: 39

Return image as an element's background

I have a JavaScript Function that creates an image:

    var imageFoo = document.createElement("img");
    imageFoo.src = dataUrl;
    imageFoo.classList.add("waveform");
    imageFoo.id = "wvf";

Now if I add:

document.body.appendChild(imageFoo);

Returns the image to the body of the page. All working. But What I try to do is to return this image as the background of an element. I tried the following:

var x = document.getElementsByClassName("mejs-time-total");
x[0].style.backgroundImage = dataUrl; //I tried with imageFoo.src too

And it won't load the image.

If I link it to one of the images on my disk, it will load the image:

x[0].style.backgroundImage = "url(https://localhost:44384/Content/images/waveform.png);

How can I make this work?

Upvotes: 0

Views: 57

Answers (1)

Beginner
Beginner

Reputation: 9095

 var imageFoo = document.createElement("img");
    imageFoo.src = "https://via.placeholder.com/350x150?text=1-3";
    imageFoo.classList.add("waveform");
    imageFoo.id = "wvf";

var x = document.getElementsByClassName("data");
x[0].style.backgroundImage = "url("+imageFoo.src+")"
<div class="data">
  sample
</div>

Upvotes: 1

Related Questions