Search code examples
cssknockout.jsknockout-sortable

Change CSS of element in after Move event of Knockout sortable


I want to change the CSS of an element once it is dragged and dropped (afterMove event) to a container using the knockout sortable library. I tried getting the ID of the div containing the element and modifying its CSS in the afterMove event as:

document.getElementById('container').style.backgroundColor="yellow";

The above code does not change the color of the moved element but the very first element in the observable array of the elements. I have attached the JS fiddler of the current situation. Is their a way of accessing the div's ID of the element which was moved so that only the css of that particular element is changed?

Attached JS fiddler


Solution

  • Add a moved property to your students

    var Student = function(id, name, gender) {
        this.id = id;
        this.name = ko.observable(name);
        this.gender = gender;
        this.moved = ko.observable(false);
    };
    

    Bind CSS for the items to use it:

    <div id="container" style="background-color: white; margin:4px;">
        <p data-bind="text: name, css:{two:moved}"></p>
    </div>
    

    Set the property after move:

    this.updateLastAction = function(arg) {
        arg.targetParent()[arg.targetIndex].moved(true);
    };
    

    http://jsfiddle.net/UdXr4/846/