jQuery toggle sort order and save to variable This works fine but I find it quite big and had hoped there was a cleaner/smaller "toggle" function or alike which I could use but it seems to be related to visibility only - and I want to set a variable (for later usage).

Can this be optimized, if I want a toggle function which should be used to sort a column (and get the value into a variable)?

jsFiddle

&lt;table&gt;
&lt;thead&gt;
  &lt;tr&gt;
    &lt;td&gt;Col 1&lt;/td&gt;
    &lt;td&gt;Col 2&lt;/td&gt;
    &lt;td&gt;Col 3&lt;/td&gt;
  &lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
  &lt;tr&gt;
    &lt;td&gt;A&lt;/td&gt;
    &lt;td&gt;B&lt;/td&gt;
    &lt;td&gt;C&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;B&lt;/td&gt;
    &lt;td&gt;C&lt;/td&gt;
    &lt;td&gt;A&lt;/td&gt;
  &lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;


And the jQuery stuff:

var column;
var order;

$('thead th').click(function () {

  // Get the current column clicked
  var thisColumn = $(this).text();

  // Check if the column has changed
  if(thisColumn == column) {
    // column has not changed

    if(order == "ascending") {
      order = "descending";
    } else {
      order = "ascending";
    }
  } else {
    // column has changed

    column = thisColumn;
    order = "descending";
  }

  // Replace text in DIV
  $("div").text("column=["+column+"], order=["+order+"]");

  // future code will use the sort order to get database
  // stuff with Ajax

});
Mostly I'ma java developer, but I think that there are a couple of things that you can do to tidy the code up.

If you do not want to store state in the DOM then you can remove the jQuery data statements and store in the global scope. If I were a jQuery developer I would probably wrap this functionality into a plugin (sortable?) and then to call it on a table with the sortabletable calss use $('.sortableTable').sortable(). It would be more reusable, more encapsulated, and less likely to cause you weird behavior if you have two tables in your page!

However here's my quick take on the above code:

var column;

$('thead th').click(function () {

    // Get the current column clicked
    var thisColumn = $(this);

    if (thisColumn.is(column)) {
        var sort = column.data("sort");
        var newSort = toggle(sort);
        column.data("sort", newSort);
    } else {
        column = thisColumn;
        column.data("sort", false);
    }
    // Replace text in DIV
    $("div").text("column=[" + column.text() + "], order=[" + column.data("sort") + "]");

});

function toggle(current) {
    return !current;
}


You could skip over setting an initial state and have toggle (and you Ajax code) work with undefined values properly (returning false).