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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.