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?
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.
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.
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.
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.
You probably want this (to make it like a normal CSS background-image declaration):
$('myObject').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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With