jQuery: lower the height of an element from top to bottom

jQuery: lower the height of an element from top to bottom

How to dynamically lower the height of an element from top to bottom with jQuery.

About two years ago I proposed a jQuery solution for dynamically lowering an element with a stated height. The proposed solution worked fine but the resulting code was rather clunky. So here's an updated version.

The solution is simple: prepend an empty element to the target element, assign a given background to the newly created element and animate its height property:


(function($) {
	$.fn.lower = function(options) {
	
		options = $.extend({
			speed: 600,
			max: '50%',
			background: '#fff'
		}, options);
		
		return this.each(function() {
			var $element = $(this);
			$element.prepend('<div class="lower"></div>');
			$('div.lower', $element).css('backgroundColor', options.background);
			
			$('div.lower', $element).animate({
				height: options.max
			}, options.speed);
		});
	};

})(jQuery);

An example:


$(function() {
	$('#content').click(function() {
		$(this).lower();
	});
});

[view-example url="http://codepen.io/gabrieleromanato/pen/CfhiH"]