Question

I want to keep a list like this draggable http://jqueryui.com/draggable/#sortable sortable in json example if I change the position to be saved and I do not like as I can raise it? sorry for my language use google translator

Was it helpful?

Solution

You can use the "stop" event to trigger a function which saves the list as a json in local storage. a working example on jsfiddle: http://jsfiddle.net/tomaspolach/S6JB6/

$(function() {

function restoreFromJSON() {
    // check for local storage support
    function supports_html5_storage() {
        // http://diveintohtml5.info/storage.html
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            return false;
        }
    }
    if (!supports_html5_storage) return
    // get json from local storage
    var json = localStorage.getItem("list")
    try {
        var items = JSON.parse( json )
    } catch (e) {
        var items = []
    }
    if (items.length==0) return
    // create list
    $( "#sortable" ).html('')
    $.each(items,function(i,value) {
        $('<li>', {
            class: 'ui-state-default',
            html: value
        }).appendTo( $( "#sortable" ) )
    })

}

function saveToJSON() {
    var items = []
    $("#sortable").children().each(function(i,el){
        var item = $(el).html()
        items.push(item)
    })

    // get a json:
    var json = JSON.stringify(items)  
    //$('body').append('json: '+json+'<br>')

    // save to local storage:
    localStorage.setItem("list", json)
}


// initialize

restoreFromJSON()

$( "#sortable" ).sortable({
    revert: true,
    stop: saveToJSON
})
$( "#draggable" ).draggable({
    connectToSortable: "#sortable",
    helper: "clone",
    revert: "invalid"
})
$( "ul, li" ).disableSelection()

})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top