Cannot set image src to dynamically created div

1.1k views Asked by At

I'm trying to set the background url of a div that was created on javascript. This will be used for Jquery Orbit slider. Here's how I do it.

var content 1 = null
$("#featured").html("<div id='content' style=''>");
content1 = document.getElementById("content");
content1.style.background="url(" + imageUrlList[0] + ")";

imageUrlList came from this.

imageUrlList.push(document.getElementById("image1Container").src)

It gets the src from another image tag. So the goal is to get the src of the image tag and set it as background of a div (content) that was created via javascript. The problem is, it is not there. I tried looking at inspect element. The url is there, I think it is in base64, not sure. But it is there. What do you think is the problem? Any ideas? Thanks!

UPDATE: I'm displaying an image when the user chooses an image on a file dialog. This image will be displayed on the image tag of image containers. These are the source images that I want to get and display them to the content div

function readURL(input, x) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();


        reader.onload = function (e) {
            if(x == 1)
            {$('#image1Container').attr('src', e.target.result);}
            else if(x == 2)
            {$('#image2Container').attr('src', e.target.result);}
            else if(x == 3)
            {$('#image3Container').attr('src', e.target.result);}
            else if(x == 4)
            {$('#image4Container').attr('src', e.target.result);}
            else
            {$('#image5Container').attr('src', e.target.result);}

        }

        reader.readAsDataURL(input.files[0]);
    }
}
3

There are 3 answers

0
AudioBubble On

It seems that imageUrlList[0] is not being enclosed in quotes. I'm not sure but maybe you can try:

content1.style.background="url('" + imageUrlList[0] + "')";
1
nopuck4you On

There doesn't seem to be enough information above but it almost looks like your using a data stream (base64) and not a true URL to the image. Make sure your background value contains all the appropriate attributes for data encoded content:

url('data:image/png;base64, [data])

src: http://www.w3.org/TR/mwabp/#bp-conserve-css-images (3.4.7.2).

0
AkshayP On

You can use this -

$('#content').css('background-image', 'url("' + imageUrlList[0] + '")');