Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

How to sort images using jquery?

I'm using a slider in which images are put according to file name and I've named my images like this

img-1, img-2, img-3, img-4, img-5, img-6, img-7, img-8, img-9, img-10

but browser is sorting like this

img-1, img-10, img-2, img-3, img-4, img-5, img-6, img-7, img-8, img-9

So how can I sort my images so in my example img-10 would go at last using jquery?

Upvotes: 1

Views: 448

Answers (3)

Mr_Green
Mr_Green

Reputation: 41872

The sorting is happening in Lexicographical order. you better add a "0" prefix to the numbers if you are sure that the images are less than 99 (I mean two digits).

Something like this:

"img-01", "img-02", "img-03", "img-04", "img-05", "img-06", "img-07", "img-08", "img-09", "img-10"

or else

use alphabets instead of numbering system.

"img-a", "img-b", "img-c", "img-d", "img-e", "img-f", "img-g", "img-h", "img-i", "img-j"

Further reading

Upvotes: 1

Ben Jacobs
Ben Jacobs

Reputation: 2526

If you're just looking to sort the image names, you can write a custom sort function using pure JS:

sorted = imageNames.sort(function(a, b) { 
      return parseInt(a.split('-')[1], 10) - parseInt(b.split('-')[1], 10) 
});

That will sort based on the numeric value found after the - character in your file names.

Upvotes: 2

George Dodge
George Dodge

Reputation: 31

This is what you are looking for (no sliding as noticed by neal).

$('img-selector').click(function(){
  $(this).parent().prepend(this);
});

Upvotes: 1

Related Questions