0

I stored a url in a javascript variable "bg_url" and I want to attach this url to a background-image property to a html element.

my html

<div id=#wrapper>
<p>test</p>
</div>

and my jQuery is like

$("#wrapper").css({ background-image: "'print(bg_url)'" });

but I do not get the variable attached to the css property. Does someone have an idea?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
boehmatron
  • 713
  • 5
  • 15

2 Answers2

4

Use camel cased property or use quotes since it contains - in the property name.

$("#wrapper").css({ backgroundImage: 'url('+ bg_url+ ')' });
// or
$("#wrapper").css({ 'background-image': 'url('+ bg_url+ ')' });

Although there is no need for # in your id attribute of the element and it's always better to use quotes to wrap the attribute value.

<div id="wrapper">

Refer : HTML attribute with/without quotes

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

I believe you should learn how CSS and JavaScript work. There are loads of mistakes:

  1. You don't have ". It should be <div id="wrapper">. And remove the #.
  2. You should concatenate using + operator.
  3. Always make sure you put it inside $(function () {}).

Your code should be:

var bg_url = "http://placehold.it/100?text=Background";
$(function () {
  $("#wrapper").css({
    backgroundImage: "url('" + bg_url + "')" // And don't forget the quotes here.
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <p>test</p>
</div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252