4

How I can sort images by dimension in JavaScript or jQuery. My code is following:

var imgsrc = '';
if (document.images.length < 1) {
    alert('No images to open');
    return;
}
for (var i = 0; i < window.parent.document.images.length; i++) {
    imgsrc + = '\n';
}

if (imgsrc != '') {
    var newwin = window.open('', '');
    newwin.document.open();
    newwin.document.write('\n' + imgsrc + '');
    newwin.document.close();
} else {
    alert('No images!')
}​

Please help me out. Thank you in advance.

VisioN
  • 143,310
  • 32
  • 282
  • 281
Alok Jain
  • 821
  • 1
  • 7
  • 12

2 Answers2

2

See here for getting image dimensions. You can sort an array like this. .sort() has an overload that takes a sort function. That is where you would compare the sizes.

Community
  • 1
  • 1
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
0

If you are using jquery:

​var images = $('img');

if ( images.length ) {
// images were found
 images.sort( function (img1, img2) { return img1.width - img2.width } );                                     
}

here is a working fiddle

tmaximini
  • 8,403
  • 6
  • 47
  • 69