WP-Mix

A fresh mix of code snippets and tutorials

Auto-Height for Ajax-Loaded Content

Here is a jQuery function for automatically setting the height of Ajax-loaded content.

This snippet originally was written for my plugin, SES Pro. When fully implemented, the script determines the height of Ajax-loaded content and sets the height of the container element.

jQuery(document).ready(function($) {
	//
	$('.ses-form').change(function() {
		var val = $(this).val();
		var id  = val.substr(val.length - 2);
		var x   = 'change';
		ses_ajax_style(id, x);
	});
	$('.ses-style').keyup(function() {
		var name  = $(this).attr('name');
		var chars = name.substr(name.length - 3);
		var id    = chars.substring(0, chars.length - 1);
		var x   = 'keyup';
		ses_ajax_style(id, x);
	});
	function ses_ajax_style(id, x) {
		$('.ses-response').empty();
		$('.ses-remember').remove();
		
		var url   = ses_ajax.ajax_url;
		var icon  = ses_ajax.ajax_loader;
		var input = $('.ses-style-' + id).val();
		var data  = {
			'action' : 'callback_style',
			'input'  : input,
		};
		if (x == 'change') $('.ses-response-' + id).html('<div class="ses-loading"><img src="'+ icon +'" alt="" style="border:0;" /></div>');
		
		$.post(url, data, function(result) {
			var response = result;
			$('.ses-response-' + id).html('<div class="ses-height">' + response + '</div>');
			$('.ses-height').css({ 'overflow':'hidden' });
			$('.ses-response-' + id).css({ height : $('.ses-height').height() });
		});
		
		if ($('.ses-remember').length == 0) {
			$('.ses-response-' + id).before('<div class="ses-remember">Remember to save your changes!</div>');
			$('.ses-remember').css({'background-color':'#ffff99','padding':'10px'});
		}
	}
});

Probably too project-specific to be of much general use, but it works great and I didn’t want to delete it entirely. So it’s posted here for good measure, hopefully others can cull some some value from it. On to the next..

★ Pro Tip:

SES Pro