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
  • 138,460
  • 30
  • 271
  • 271
Alok Jain
  • 681
  • 1
  • 6
  • 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
  • 23,638
  • 8
  • 74
  • 112
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,284
  • 6
  • 45
  • 68