How can I bind the CSS background-image property ?

How can I bind the CSS background-image property ?

Asked on December 11, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

        By documentation , Using the  Javascript name is better for the style everyone want to control.

        This means that using the backgroundImage rather than background-image.

        Something like this:

    <div data-bind="foreach: itemList">
        <div data-bind="style: { backgroundImage: 'url(temp.png)' }">some text</div>
    </div>
    
    Answered on December 11, 2018.
    Add Comment

       If binding is not done  to a ko.observable property then don’t try the  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>
    

    Use the  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>
    

    Answered on December 11, 2018.
    Add Comment

        Use this method  to 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() + "')"}});
        }
    };
    

        In html :

    <div data-bind="backgroundImage: image"></div>
    
    Answered on December 11, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.