Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery javascript custom sort procedure works in Firefox, but IE doesn't seem to get it... (copy-paste example code)

i've built this sample code based on a real problem I have in an application. I've got a custom sort procedure to sort jQuery arrays. A container contains a list of items with special attributes.

For sorting:

  1. Loads all items in temp array
  2. Clears the container
  3. Sorts the temp array into a new array
  4. Append sorted items to container

Somehow Firefox knows how to sort but IE doesn't. Can somebody tell me what isn't working properly?

(you can copy-paste the html below into a empty .html file, it should work immediately)

<html>
<head>
<script type="text/javascript" 
    src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
    jQuery.fn.sort = function() {  
        return this.pushStack( [].sort.apply( this, arguments ), []);  
    } 

    function DoTheSort() {
        //Fetch elements in jQueryElement
        var sortableArray = $('#sortables').find('div.sortable');

        //Clear the sortables container
        $('#sortables').empty();

        //Sort the array
        var sortedArray = $(sortableArray).sort(sortProcedure);

        //Append sorted items
        jQuery.each(sortedArray, function() {
            alert($(this).attr("sortvalue"));
            $('#sortables').append(this);                
        });
    }

    function sortProcedure(a, b) {
    var value1 = parseInt($(a).attr("sortvalue"));
    var value2 = parseInt($(b).attr("sortvalue"));
        return value1 > value2;
    }


    </script>
</head>
<body>

    <a href="javascript:DoTheSort();">Sort</a>

    <div id="sortables">
        <div class="sortable" sortvalue="5">5</div>
        <div class="sortable" sortvalue="1">1</div>
        <div class="sortable" sortvalue="4">4</div>
        <div class="sortable" sortvalue="1">1</div>
        <div class="sortable" sortvalue="2">2</div>
        <div class="sortable" sortvalue="9">9</div>
        <div class="sortable" sortvalue="3">3</div>
    </div>



</body>
</html>
like image 746
Ropstah Avatar asked Jun 04 '09 11:06

Ropstah


1 Answers

Your sort procedure is subtly wrong: you need to account for equalities as well, and boolean is not the correct return type (see addendum).

Do this:

return value1 - value2;

instead of:

return value1 > value2;

Addendum:

The general form of a sort comparison function f(A,B) needs to return > 0 if A > B, < 0 if A < B, and 0 if no alteration needs to occur. Returning a boolean gets you caught by falsey values not representing what you think they do.

like image 107
annakata Avatar answered Sep 21 '22 22:09

annakata