I have an image URL in a imageUrl
variable and I am trying to set it as CSS style, using jQuery:
$(\'myObject\').css(\'background-image\', image
Here is my code:
$('body').css('background-image', 'url("/apo/1.jpg")');
Enjoy, friend
Further to the other answers, you can also use "background". This is particularly useful when you want to set other properties relating to the way the image is used by the background, such as:
$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");
You probably want this (to make it like a normal CSS background-image declaration):
$('myObject').css('background-image', 'url(' + imageUrl + ')');
Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:
$(this).css({'background-image':'url(' + imageUrl + ')'})
You'll want to include double quotes (") before and after the imageUrl like this:
$('myOjbect').css('background-image', 'url("' + imageUrl + '")');
This way, if the image has spaces it will still be set as a property.
Try modifying the "style" attribute:
$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');