views:

93

answers:

2

I am newbie to jQuery, can someone explain what this code does:

$(document).ready(function() {
    var order = null;
    $("#order-list").load(location.href+" #order-list>*","");   
    $("#order-list").sortable({
      handle : '.handle',
      update : function (e, ui) {
             order = $(this).sortable('serialize');
         $("#info").load("process-sortable.php?"+order);
    }
    });

});
A: 

load means "Replace the contents of anything in the matched set (in this case, the element with id order-list) with whatever HTML comes back from the URI that I pass."

sortable is a plug-in, not part of jQuery itself. The object passed is the options argument for the plug-in. Refer to the docs for sortable for the meaning of properties of the options object. For handle, it says:

Restricts sort start click to the specified element.

Now, this code looks like a bug to me. It does an asynchronous load, but then calls sortable without waiting for the load to complete. load takes a callback, so you'd generally use that for any operation you want to perform on the loaded HTML.

Craig Stuntz
So If I get it correctly, the first load clears the content. Why do we need to construct with location.href, and a space as prefix ?
Pentium10
@Pentium10 the first load seems strange to me since it is replacing the content with another call to the same page getting the content. This is sort of a mini-refresh if you will.
Hogan
+4  A: 

Straight from the API docs , "Loading Page Fragments":

"The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to fetch only part of the document:

$('#result').load('ajax/test.html #container');

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded."

andras