Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery min/max property from array of elements

Is there a simple way to find the min/max property from an array of elements in jQuery?

I constantly find myself dynamically resizing groups of elements based on the minimum and maximum counterparts. Most of the time this pertains to the width and/or height of an element but I'm sure this could be applied to any property of an element.

I usually do something like this:

var maxWidth = 0;  $('img').each(function(index){ if ($(this).width() > maxWidth) { maxWidth = $(this).width(); } }); 

But it seems like you should be able to do something like this:

var maxWidth = $('img').max('width'); 

Does this functionality exist in jQuery or can someone explain how to create a basic plugin that does this?

Thanks!

like image 734
user624598 Avatar asked Feb 19 '11 18:02

user624598


1 Answers

Use Fast JavaScript Max/Min - John Resig

Example with three logos of google, yahoo and bing.

HTML

<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" alt="Google Logo" /><br/> <img src="http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png" alt="Yahoo Logo" /><br/> <img src="http://www.bing.com/fd/s/a/h1.png" alt="Bing Logo" /> 

Javascript

$(document).ready(function(){     // Function to get the Max value in Array     Array.max = function( array ){         return Math.max.apply( Math, array );     };      // Function to get the Min value in Array     Array.min = function( array ){        return Math.min.apply( Math, array );     };      //updated as per Sime Vidas comment.     var widths= $('img').map(function() {         return $(this).width();     }).get();      alert("Max Width: " + Array.max(widths));     alert("Min Width: " + Array.min(widths)); }); 

P.S: jsfiddle here

like image 64
naveen Avatar answered Sep 24 '22 17:09

naveen