Search code examples
javascriptbackground-imagetumblr

Javascript insert image as a div background


I'm trying to insert my lastest tumblr post image directly as the background-image of a div on my website.

I'm able to add an image src with this code

<img border='0' style='margin:0' width='100%' id='TumblrMagic' src='' alt='' />
    <script type='text/javascript' src='http://myblog.tumblr.com/api/read/json?number=1&type=photo'></script>
    <script type='text/javascript'>
            document.getElementById('TumblrMagic').setAttribute('src', tumblr_api_read.posts[0]['photo-url-500']);
    /script>

But for style reason, I'd like to be able to put it as a background-image of a div. I'm digging around this

<div id="TumblrMagic"></div>
<script type='text/javascript'>
        document.getElementById('TumblrMagic').css('background-image', 'url(' + imageUrl + ')');
</script>

Now I'm trying to replace imageUrl with the code that loads the image tumblr_api_read.posts[0]['photo-url-500'] but I'm not fluent in javascript. Anyone can give me a hand?


Solution

  • Append img element to div:

    <script type='text/javascript'>
        var div = document.getElementById('TumblrMagic');
        var image = document.createElement("img");
            image.src = tumblr_api_read.posts[0]['photo-url-500'];
        div.appendChild(image);
    </script>
    

    or set background image to div:

    <script type='text/javascript'>
        var  image = tumblr_api_read.posts[0]['photo-url-500'];
        var div = document.getElementById('TumblrMagic');
            div.style.backgroundImage = 'url(' + image + ')';
            div.style.width = '100%'; //change it or apply by CSS
            div.style.height = '768px'; //change it or apply by CSS
        </script>