Search code examples
jqueryfunctionheightwidthargument-passing

Passing jquery function as variable parameter to the custom function


I am writing a function which calculates the biggest height / width and makes the elements of the same height / width. I want to pass 2 parameters to this function:

1. The selector, which can be(element, class )
2. jQuery `width()` / `height()` function

and the desired result should be the function which looks like..

Eg 1. equalDimensions('.class', width() ); OR
Eg 2. equalDimensions( div, height() );

and based on what is passed to the function width() / height() it will calculate the biggest height / width and make all the selectors which is passed as a first parameter equal width / height.

Being new to jQuery, I am struggling with putting it into code.

This is what I have tried so far...

var equalDimension = function(  selector,  fn ){
    var dimension = fn();
    var biggestDimemsion = 0;
    $(selector).each(function(){
        if($(this).dimension > biggestDimemsion){
            biggestDimemsion = $(this).dimension;
        }
    });
    $(selector).each(function(){
        $(this).dimension(biggestDimemsion);
    });
};

Solution

  • I wrote a quick example of how I would approach this problem:

    http://jsfiddle.net/3NRah/

    var equalDimension = function (selector, fn) {
        var $elements = $(selector),
            dimensions = $elements.map(function (i) {
                return $elements.eq(i)[fn]();
            }),
            maxDimension = Math.max.apply(Math, dimensions);
        $elements[fn](maxDimension);
    };
    
    equalDimension('div', 'height');
    

    This assumes that you are passing the name of a jQuery function, rather than the function itself. If you want to pass the actual function, it would look like this:

    http://jsfiddle.net/3NRah/1/

    var equalDimension = function (selector, fn) {
        var $elements = $(selector),
            dimensions = $elements.map(function (i) {
                return fn.call($elements.eq(i));
            }),
            maxDimension = Math.max.apply(Math, dimensions);
        fn.call($elements, maxDimension);
    };
    
    equalDimension('div', $.fn.height);
    

    Edit: In terms of creating a clean UI for this, I would most-likely add this as in the following JSBin.

    http://jsbin.com/pogujozane/edit?js,output

    $.fn.equalDimension = function (fn) {
        var $elements = $(this),
            dimensions = $elements.map(function (i) {
                return $elements.eq(i)[fn]();
            }),
            maxDimension = Math.max.apply(Math, dimensions);
        $elements[fn](maxDimension);
    };
    $.fn.equalHeight = function () {
      return $(this).equalDimension('height');
    };
    $.fn.equalWidth = function () {
      return $(this).equalDimension('width');
    } 
    

    So that it could be called like:

    $('div').equalHeight();