Is it possible to make a style background-image binding?
I tried this code:
<div data-bind="foreach: itemList">
<div data-bind="style: { background-image: 'url:(temp.png)' }">some text</div>
</div>
I also tried backgroundImage
, without quotes in url
, without :
after url
, but it's still not working. All the others, like color
or backgroundColor
bindings are working perfectly.
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.
The background image can be set using the background-image property that is used to set one or more background images for an element.
As the simplest solution. That is: Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
To control the position of an image in the background, use the background-position property.
As stated in the documentation, you need to use the Javascript name for the style you want to control.
This means that you would have to use backgroundImage
instead of background-image
.
Something like this:
<div data-bind="foreach: itemList">
<div data-bind="style: { backgroundImage: 'url(temp.png)' }">some text</div>
</div>
I'm not sure why everyone (except Sujesh) is answering this question and still hard coding the temp.png
. If you are not binding to a ko.observable
property then don't use data-bind
. Just use the standard style property of the html element.
<div data-bind="foreach: itemList">
<div style="background-image: url('temp.png');">some text</div>
</div>
For data binding to get the url I wish Sujesh Arukil's answer worked for me but it didn't. If anyone has that working, please enlighten me.
Here is what worked for me but I don't care for it. I used a computed to get the value of the background-image.
In the view model
self.imageUrl = ko.observable();
self.bgImageUrlStyle = ko.computed(function() {
return "url(" + self.imageUrl() + ")";
});
In the HTML
<div data-bind="style: { 'background-image': bgImageUrlStyle }">
</div>
By the way, you can set up a custom binding to make the syntax less unwieldy:
ko.bindingHandlers.backgroundImage = {
update: function(element, valueAccessor) {
ko.bindingHandlers.style.update(element,
function(){return {backgroundImage: "url('" + valueAccessor() + "')"}});
}
};
Then in your HTML you can do
<div data-bind="backgroundImage: image"></div>
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