0

I'm trying to apply a background image using a style tag on a div that's reference in JavaScript. I'm sure it's something to do with the quotations around the image variables. Any help would be greatly appreciated.

function appendData () {
 var image = "http://domain.com/image.jpg";
 var html = '<div class="itemImage" style="background-image:url(' + image +    ');"></div>';
 $('.container').append(html);
}
4
  • you should tag jQuery as well, since you are using it in your last line :) Commented Jul 8, 2016 at 14:43
  • What is the CSS for itemImage? I am interested to know the height and width of the div. Also try surrounding the url with double quotes: url("' + image + '") Commented Jul 8, 2016 at 14:44
  • Guessing: is it a cross-origin problem? Commented Jul 8, 2016 at 14:47
  • Have you checked if the image is larger than the div you have put it inside? It could be rendered but due to size you might only be seeing a small portion of the empty space around it. codepen shows that it should work as is assuming no cors or background-size issues Commented Jul 8, 2016 at 14:53

2 Answers 2

2

I would consider changing your approach slightly. Sure, you can append the html to your container OR you could change the property of the itemImage without re-writing it every time.

If you build the itemImage div into that container you could do this instead

function appendData () {
  var image = "http://domain.com/image.jpg";
  $(".itemImage").css("background-image", image);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I never thought of that, that's some good advice. Thanks John :)
No prob! I try to avoid inserting HTML whenever possible.
1
function appendData () {
 var image = "http://domain.com/image.jpg";
 var html = '<div class="itemImage" style="background-image:url(\'' + image +    '\');"></div>';
 $('.container').append(html);
}

1 Comment

Marco - Perfect. Thank you! - I can accept the answer in 6 minutes :)

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.