El evento ‘onresize’ se lanza cuando un elemento HTML cambia de tamaño. Pero tenemos el problema de que sólo Internet Explorer lo lanza en el momento del cambio de tamaño del elemento, mientras que el resto de navegadores lo hace solo al cambiar el tamaño de la ventana del navegador.

Este pequeño plugin jQuery ayudará a detectar cambios de tamaño en cualquier elemento HTML, lanzando un evento onResize ‘casi’ en el momento del cambio.

$.fn.addOnResizeEvent = function(custom_options) {
 
	var options = {
		timeInterval : 100,
		forceIE : false
	}
 
	$.extend( custom_options, options );
 
	// Soporte nativo IE
	if ($.browser.ie && !options.forceIE) return;
 
	return this.each( function() {
 
		var target = $(this);
		var lw, lh;
 
		var interval = setInterval( function() {
 
			var w = target.width(),
				h = target.height();
 
			if (!lw == undefined) lw = w;
			if (!lh == undefined) lh = h;
 
			if ( lw != w || lh != h )
			{
				lw = w;
				lh = h;
				target.trigger( "resize" );
			} 
 
		}, options.timeInterval );
 
	} );
 
};

Y su modo de uso:

$("div.miDiv").addOnResizeEvent()
 
$("div.miDiv").resize( function() {
	alert("Cambié de tamaño");
} );

En caso de estar navegando con Internet Explorer este plugin no tendrá efecto dejando la activación del evento nativa. Sin embargo, puede forzarse pasandole un parametro ‘forceIE‘ como ‘true‘.

Además, permite modificar el tiempo entre chequeos de tamaño por el parámetro ‘timeInterval‘, indicando la espera en milisegundos.

El modo de asignar los parámetros es el siguiente:

$("div.miDiv").addOnResizeEvent({
	timeInterval : 200,
	forceIE : true
})

Una última recomendación, y por temas de rendimiento, es la de asignar esta función solamente a aquellos elementos que quiera registrarse un cambio de tamaño.

Otros posts

No hay comentarios»

RSS feed de los comentarios. TrackBack URL

Deja un comentario

Please copy the string sCNP1Z to the field below: