Thinking in programming

Things I like to talk about programming

Posts Tagged ‘basic jquery plugin

jquery.synchHeights an introductory plugin to the jQuery-plugins-creation world

leave a comment »

This time I’m going to “move a bit back in the time” in order to show how to create a very basic jQuery plugin, hopefully, it will be useful for those persons looking to get into the jQuery-plugins-creation world.

The plugin is intended to synchronize the heights of the elements matched by the given CSS selector.
The functionality is going to be very simple, it will just assign the tallest element’s height to all the
elements in the set. It should take advantage of all the power of the jQuery selectors and its usage
should be very straightforward, in short, something like that:

$('.element1-class, #element2_id', more_CSS_selectors').synchHeights();

So, lets go to the action:

/**
 * jQuery.synchHeights plugin v1.0
 * Copyright 2010, Roger Padilla - @rogerjose81@gmail.com
 * Licensed under Apache License 2.0
 * This plugin is intended to synchronize the heights of the elements matched
 * by the given CSS selector. The functionality of this plugin is very simple,
 * it just assigns the tallest element's height to all the elements in the set.
 */
$.fn.synchHeights = function() {

	// the 'this' object is a jQuery object which keep reference to DOM-elements in the set
	var elemsSet = this;
	
	// calls the function which obtains the greater hight
	var maxHeight = getMaximumHeight(elemsSet);
	
	// calls the function used to synchronize the heights
	synchHeights(elemsSet, maxHeight);
	

	// loops through the elements set to obtain the greater height
	function getMaximumHeight(elemsSet){
		var maxHeight = 0, item;
		elemsSet.each(function(){
			item = $(this);
			if (item.height() > maxHeight) {
				maxHeight = item.height();
			}
		});
		return maxHeight;
	}

	/*
	 * Synchronizes the heights of the elements in the set by using
	 * the calculated maximun-height
	 */
	function synchHeights(elemsSet, maxHeight) {
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) {
			elemsSet.css({'height': maxHeight});
		}
		elemsSet.css({'min-height': maxHeight});
	}

	// returns 'this' to be able to use chaining selectors
	return this;
};

Written by roger.padilla

July 20, 2010 at 13:15