How to make a self contained jQuery plugin that finds the tallest image height?

Posted by Jannis on Stack Overflow See other posts from Stack Overflow or by Jannis
Published on 2010-04-05T06:47:23Z Indexed on 2010/04/05 8:33 UTC
Read the original article Hit count: 231

Filed under:
|

I have been trying to make this to be a little jQuery plugin that I can reuse in the future without having to write the following into my actions.js file in full.

This works when loaded in the same file where I set the height using my variable tallest.

var tallest = null;
$('.slideshow img').each(function(index) {
  if ($(this).height() >= tallest ) {
    tallest = $(this).height();
  }
});
$('.slideshow').height(tallest);

This works and will cycle through all the items, then set the value of tallest to the greatest height found. The following however does not work:

This would be the plugin, loaded from its own file (before the actions.js file that contains the parts using this):

(function($){
  $.fn.extend({
    tallest: function() {
      var tallest = null;

      return this.each(function() {
        if ($(this).height() >= tallest ) {
          tallest = $(this).height();
        }
      });
    }
  });
})(jQuery);

Once loaded I am trying to use it as follows:

$('.slideshow img').tallest();
$('.slideshow').height(tallest);

However the above two lines return an error of 'tallest is undefined'. How can I make this work? Any ideas would be appreciated. Thinking about this even more the perfect usage of this would be as follows:

$('.container').height(tallest('.container item'));

But I wouldn't even know where to begin to get this to work in the manner that you pass the object to be measured into the function by adding it into the brackets of the function name.

Thanks for reading,

Jannis

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about plugins