0

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?

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately, it ads the picture directly and not as a background-image of my div.
1

Try this :

var imageUrl = tumblr_api_read.posts[0]['photo-url-500'];

7 Comments

I was just trying this a moment ago but I only got a Uncaught TypeError: undefined is not a function...
Can you put this before : console.log(tumblr_api_read); and tell me what you'll fine in the console ?
I can read this Object {tumblelog: Object, posts-start: 0, posts-total: 82, posts-type: "photo", posts: Array[20]}
So I don't see a problem. Can you try this to be sure ? console.log(tumblr_api_read.posts[0]); and see if "photo-url-500" is in there ?
console.log(imageUrl) ? And I think document.getElementById('TumblrMagic').src = imageUrl; would be more appropriate.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.