Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background-image using jQuery CSS property

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', imageUrl); 

This seems to be not working, as:

console.log($('myObject').css('background-image')); 

returns none.

Any idea, what I am doing wrong?

like image 378
Blankman Avatar asked Feb 04 '09 16:02

Blankman


People also ask

How do you set a background image and property?

The background-image property sets one or more background images for an element. By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

How can set background color in JQuery?

To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.

What is background property in CSS?

The background property in CSS allows you to control the background of any element (what paints underneath the content in that element). It is a shorthand property, which means that it allows you to write what would be multiple CSS properties in one.

Can you put a background image in a div?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.


2 Answers

You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')'); 
like image 172
Greg Avatar answered Oct 09 '22 09:10

Greg


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.

like image 41
Arosboro Avatar answered Oct 09 '22 08:10

Arosboro