Skip to content

Instantly share code, notes, and snippets.

@ghing
Created January 24, 2012 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghing/1672907 to your computer and use it in GitHub Desktop.
Save ghing/1672907 to your computer and use it in GitHub Desktop.
Skeleton for a jQuery plugin to get elements matching heights
/**
* jQuery Plugin: "keepup"
* by: Geoffrey Hing <geoffhing@gmail.com>
*
* Copyright (c) 2012 Geoffrey Hing
* Licensed under MIT (http://www.opensource.org/licenses/mit-license.php)
*
* Description: Sets the height of one element equal to another.
* Dependencies: jQuery library.
* Usage Example: $('.element-to-resize').keepUp('matchHeight', $('.element-to-match'));
*/
(function( $ ) {
var methods = {
init: function () {
},
matchHeight: function (el) {
var newMinHeight = el.height();
return this.each(function() {
var $this = $(this);
$this.css('min-height', newMinHeight);
});
},
matchTallest: function (el) {
// Assume the first target element is the tallest.
var newMinHeight = el.height();
el.each(function() {
// See if any of the matching elements is actually taller
var $this = $(this);
if ($this.height() > newMinHeight) {
newMinHeight = $this.height();
}
});
this.each(function() {
// See if any of the matching elements is actually taller
var $this = $(this);
if ($this.height() > newMinHeight) {
newMinHeight = $this.height();
}
});
el.each(function() {
var $this = $(this);
if ($this.height() < newMinHeight) {
// We were wrong, the target element is not the tallest.
console.debug('Resizing ' + $this.attr('class'));
console.debug('Resizing ' + $this.attr('class') + ' from ' + $this.height());
el.css('min-height', newMinHeight);
el.height(newMinHeight);
console.debug('New height is ' + $this.height());
}
});
console.debug("The tallest element is " + newMinHeight);
return this.each(function() {
var $this = $(this);
if ($this.height() < newMinHeight) {
console.debug('Resizing ' + $this.attr('class') + ' from ' + $this.height());
$this.css('min-height', newMinHeight);
el.height(newMinHeight);
console.debug('New height is ' + $this.height());
}
});
}
};
$.fn.keepUp = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.chiara' );
}
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment