0

Hey everybody please help I can't find the error

when I press sort...it sort again and again forever

html:

<div class="unsorted">
    <div class="labelimagediv" rel="5"> 
      Div 5 here 
    </div> 
    <div class="labelimagediv" rel="3"> 
       Div 3 Here 
    </div> 
     <div class="labelimagediv" rel="4.5"> 
       Div 4.5 here 
    </div>
    <div class="labelimagediv" rel="4">
      Div 4 Here
     </div> </div>
<button class="btnSort">Sort</button>

javascript:

$("button.btnSort").click(function () {
    var item1 = $('div.labelimagediv')[0];
    var sortedDivs = $(".unsorted").find(item1).toArray().sort(sorter);
    $.each(sortedDivs, function (index, value) {
        $(".unsorted").append(value);
    });
});

function sorter(a, b) {
    return a.getAttribute('rel') - b.getAttribute('rel');
};
5
  • Can you rephrase the question? It doesn't make sense. Commented Sep 12, 2013 at 22:08
  • try it jsfiddle.net/NBKPk when I press the sort botton it still sorting and I want only to sort from 1 to 3 one time only Commented Sep 12, 2013 at 22:12
  • check this stackoverflow.com/questions/2351635/… Commented Sep 12, 2013 at 22:15
  • 1
    At first glance, it is NOT sorting, just moving 1 element. The error seems to be in between the keyboard and the chair. Commented Sep 12, 2013 at 22:16
  • I'm not like you "programmer" I'm trying to make my things by myself Commented Sep 12, 2013 at 22:23

2 Answers 2

4

That's because you are sorting one element by selecting the first element $('div.labelimagediv')[0];, try this:

$("button.btnSort").click(function () {
    $('div.labelimagediv').sort(function(a, b) {
       return a.getAttribute('rel') > b.getAttribute('rel');
    }).appendTo(".unsorted");
});

JsFiddle fork here

Sign up to request clarification or add additional context in comments.

Comments

1
var item1 = $('div.labelimagediv')[0];

^^ that's just one single element ?

It should be :

$("button.btnSort").click(function () {
    var sortedDivs = $('.labelimagediv', '.unsorted').get();
    sortedDivs.sort(function(a,b) {
        return a.getAttribute('rel') - b.getAttribute('rel');
    });
    $.each(sortedDivs, function (index, value) {
        $(".unsorted").append(value);
    });
});

FIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.