Noticias Weblogs Foros Wiki Código

RecorteX

» JavaScript
333 usuarios y 204 recortes de código
Usuario

Contraseña
Crear cuenta
Estás viendo los recortes de la etiqueta JavaScript

RSS
Recortes: 21

Etiquetas relacionadas:
html
XMLHttpRequest
Ajax
css
JS
imagenes
variable
redireccion
forma
altura
tiempo
jquery
xhtml
redirecicon
head
button
trim
declarada
scroll
historia
cadena
vacio
php
div
temporizado
checkbox
validar
radio
electronico
texto
correo

Bloques de la misma altura con jquery

Yo había creado bloques de la misma altura con jquery (es muy sencillo) pero esta función lo hace de modo genérico (se le pasa la lista de elementos).

Visto en Sentido Web

 
function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
 

Ejemplo de llamada:

 
$(document).ready(function() {
    equalHeight($(".recent-article"));
    equalHeight($(".footer-col"));
});
 

Generar funciones de accesibilidad de manera rapida en un formulario

El codigo que posteo es uno que yo uso, tal vez no sea la mejor solucion mas quiero compartirla con Uds., para mi se ha vuelto una manera muy efectiva y rapida de dar cierta usabilidad a mis formularios sin tanta complicacion ademas de aplicar javascript no intrusivo

 
  function prepararFormulario()
{		
	var txts=document.getElementsByTagName("INPUT");
	for(var i=0;i<txts.length;i++)
	{	var txt=txts[i];
	
		txt.onfocus=function()
		{	this.className='focused'; 
			if(this.type=="text")
			{
				/*aun me falta terminar la implementacion, estoy buscando un 
codigo crossbrowser que al obtener el foco 
seleccione el texto de la caja de texto*/
			}
		}
		
		txt.onblur=function()
		{	this.className=''; }
		
		/////////////////////////////////////////
		//Los navegadores basados en estandares automaticamente crean el Objeto Event
		//, a pesar que este no sea definido de manera explicita
		//asi en esta funcion, al enviar e, FF automaticamente genera un objeto Event.
		txt.onkeypress=function(e)
		{ 						
				if(!e)var e=window.event;			
				var xId=new String;
				xId=this.id;
				//(!document.all) ? alert(e.srcElement) : alert(e.target);
				switch(xId.substring(0,3))
				{	
					case 'txt':					
						return soloCadenas(e);
						break;				
					case 'num':
						return soloNumeros(e);					
						break;
					case 'fec':
						return soloFechas(e);					
						break;
					case 'fic':
						return soloFechas_Input(e);					
						break;		
				}
		}
			
 
	}
	
	var sels=document.getElementsByTagName("SELECT");
	for(var i=0;i<sels.length;i++)
	{	var sel=sels[i];
		sel.onfocus=function()
		{	this.className='focused'; }
		
		sel.onblur=function()
		{	this.className=''; }
	}	
}
 

Funcion en JavaScript que recoge los valores de un formulario

ya se que esto mismo lo hace el SUBMIT de un formulario cuando se envia por metodo POST, pero en caso quieran enviarlo por metodo GET esto puede serles de ayuda sobre todo si van utilizar Ajax.

 
  function getValues(obj)
{
	var getstr="";
	for (var i=0; i<obj.childNodes.length; i++) {
		if (obj.childNodes[i].tagName == "INPUT") {
			if (obj.childNodes[i].type == "text") {
			   getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
			}
			if (obj.childNodes[i].type == "checkbox") {
			   if (obj.childNodes[i].checked) {
				  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
			   } else {
				  getstr += obj.childNodes[i].name + "=&";
			   }
			}
			if (obj.childNodes[i].type == "radio") {
			   if (obj.childNodes[i].checked) {
				  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
			   }
			}
		 }   
		 if (obj.childNodes[i].tagName == "SELECT") {
			var sel = obj.childNodes[i];
			getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
		 }
		 
		 if(obj.childNodes[i].tagName=="FIELDSET" || obj.childNodes[i].tagName=="DIV" || obj.childNodes[i].tagName=="UL" || obj.childNodes[i].tagName=="LI")
		 {
			getstr+=getValues(obj.childNodes[i]);
		 }
	}	
	 return getstr;
}
 

Como observan el resultado es un String, de tal manera que uds pueden llamar esta funcion y en su funcion o metodo que llaman una pagina mediante Ajax pueden enviar asi

 
//Donde obj es el elemento padre del formulario
var params=getValues(obj)
getPagina(url + params)
 

Cargar combos con Ajax

No se uds. pero antes hacer combos que se cargaran donde uno dependia de otro era algo engorroso, claro que habia varios metodos, se podia usar iframes o recargar la pagina, aunque sinceramente ninguno de esos me parece muy bueno, hace poco necesite hacer algo asi para una web app, asi que le digo como lo hice, no se si sera lo mejor pero talvez a alguien le sirva.

Por si acaso esto esta hecho con PHP y MySQL

Primero tenemos nuestro formulario

Esas dos son clases donde la primera permite manejar la Base de datos, esa clase la postee hace un tiempo aqui.( http://www.recortex.com/recorte/177 )
Todo lo que viene a continuacion esta dentro de un solo archivo formulario.php

 
<?php 	
        include("./cls/clsManejaBD.php"); 
	include("./cls/clsUbicacion.php"); 
?>
 
 
<form action="./actions/registrar_evento.php" method="post" id="frmRegistraEvento">
<fieldset><label>Departamento</label>
         <?php /*instancio la clase y llamo a un metodo de la misma que va a generar la lista de departamentos*/ 
               $u=new Ubicacion(); $u->Generar_Combo_Departamentos(); 
         ?>
</fieldset>
<fieldset><label>Provincia</label><div id="cmbProvincia">Provincia</div></fieldset>
<fieldset><label>Distrito</label><div id="cmbDistrito">Distrito</div></fieldset>
<fieldset><label>Fecha</label><input type="text" name="txtFecha" value="dd/mm/aaaa" size="10" maxlength="10"/></fieldset>
<fieldset><label>Tema</label><input type="text" name="txtTema" value="tema tratado"/></fieldset>
<fieldset><label>Publico</label><input type="text" name="txtPublico" value="publico atendido"/></fieldset>
<fieldset><label>Lugar</label><input type="text" name="txtLugares" value="lugar"/></fieldset>
<fieldset><label>Cantidad</label><input type="text" name="txtCantidad" value="0"/></fieldset>
<fieldset><label>N&deg; de Informe</label><input type="text" name="txtInforme" value="N&deg; de Informe" /></fieldset>
<fieldset><label>Fecha de Informe</label><input type="text" name="txtFecha_Informe" value="dd/mm/aaaa" size="10" maxlength="10"/></fieldset>
<fieldset><input type="button" name="aceptar" value="aceptar"/> <input type="button" name="borrar" value="borrar"/></fieldset>
</form>
 

Cuando se vea esta pagina el navegador reemplazara donde aparece nuestro codigo php por esto

 
<select id="departamento" onchange="cambio(id,2);">
<option> Amazonas</option>
<option> Ancash </option>
<option> Arequipa </option>
...
</select>
 

ahora viene la parte de javascript, yo tengo una funcion denominada cambio() dentro de la cual valido el destino y que pagina cargar, lo que sigue pueden ponerlo en la misma pagina o en un archivo js aparte

 
function cambio(id, dest)
{	var index=document.getElementById(id).selectedIndex;
	var url;
	var detino;
       /*de acuerdo al combo que cambie carga el dato del siguiente combo
combo "departamento" carga "provincias" y "provincias" carga "distritos" */
	if(dest==2)
		{ 
			url="cargar_provincias.php?idDep=" + (index+1); /*a la variable se le suma 1 ya que el indice del combo empieza en 0*/
			destino='cmbProvincia';
		}
		
	if(dest==3)
		{ 	url="cargar_distritos.php?idProv=" + (index+1) + "&idDep=" + (document.getElementById('departamento').selectedIndex + 1);
			destino='cmbDistrito';
		}
		
	cargarDatos(url, "action", destino);//esta es una funcion que llama al ajax
}
 

Bueno aunque yo tengo separado en archivos diferentes en este caso vamos a decir que tanto la funcion de arriba como la funcion para ajax se encuentra en el mismo archivo

 
function cargarDatos(pagina, dir, target)	
{	var page = false;
	var target;
	var url;
	url="./" + dir + "/" + pagina;
    if (window.XMLHttpRequest)
    {
        // Si es Mozilla, Safari etc
        page = new XMLHttpRequest ();
    } else if (window.ActiveXObject)
    {
        // pero si es IE
        try 
        {
            page = new ActiveXObject ("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            // en caso que sea una versi&oacute;n antigua
            try
            {
                page = new ActiveXObject ("Microsoft.XMLHTTP");
            }
            catch (e)
            {
            }
        }
    } 
    else
	{	return false;}
	
    page.onreadystatechange = function ()
    {
        // funci&oacute;n de respuesta
		if (page.readyState != 4) {
			document.getElementById (target).innerHTML= '<div id="loader"><img src="./img/ajax-loaderC.gif" > Cargando datos...</div>';
		}else{
			//window.setTimeout("cargarpagina(page);",2000); //pretendemos demorar la respuesta unos segundos
			cargarpagina(page, target);
		} 		
    }
	
    page.open ('GET', url, true); // asignamos los m&eacute;todos open y send
    page.send (null);	
 
}
 
function cargarpagina(page, target)
{
    if (page.readyState == 4 && (page.status == 200 || window.location.href.indexOf ("http") == - 1))
		document.getElementById (target).innerHTML = page.responseText;
}
 

por ultimo debemos tener nuestros archivos php, yo los tengo en una carpeta llamada “action”
aqui le muestro el que carga los distritos para que se den una idea

 
<?php
	include("../cls/clsManejaBD.php"); 
	include("../cls/clsUbicacion.php"); 
	$id_departamento=$_GET['idDep'];
	$id_Provincia=$_GET['idProv'];
	$u=new Ubicacion(); $u->Generar_Combo_Distritos($id_departamento,$id_Provincia);
?>
 

por ultimo no se uds. pero a veces me ha pasado a mi que en tutoriales como estos no ponen el codigo completo php y uno se pierde, asi que aqui les pongo el codigo de la clase Ubicacion.

getSQL($query);		
		return $rs;
	}
	
	function Generar_Combo_Departamentos()
	{ $rs=$this->ListarDepartamentos();
		if (mysql_num_rows($rs)>0)
			{	echo "<select id='departamento' onchange='cambio(id,2);'>";				
	 			while($data=mysql_fetch_array($rs,MYSQL_NUM))
				{	echo  "<option> $data[1] </option>";			
				}
				echo "</select>";
 			}	
		else
			{	echo "no existen datos para mostrar";
			}
		mysql_free_result($rs);	
	}
	
	function ListarProvincias($fk_departamento)
	{	
		$dbm=new ManejaBD;
		$query="SELECT idProvincia, nombre FROM Provincia where fk_Departamento=$fk_departamento";		
		$rs=$dbm->getSQL($query);			
		if($rs)
		{	return $rs;
		}
		
	}
	
	function Generar_Combo_Provincias($idDepartamento)
	{ $rs=$this->ListarProvincias($idDepartamento);
		if (mysql_num_rows($rs)>0)
			{	echo "<select id='provincia' onchange='cambio(id,3);'>";				
	 			while($data=mysql_fetch_array($rs,MYSQL_NUM))
				{	echo  "<option> $data[1] </option>";			
				}
				echo "</select>";
 			}	
		else
			{	echo "no existen datos para mostrar";
			}
		mysql_free_result($rs);	
	}
	
	function ListarDistritos($fk_departamento, $fk_provincia)
	{	
		$dbm=new ManejaBD;
		$query="SELECT DISTINCT idDistrito, nombre FROM Distrito where fk_Departamento=$fk_departamento and fk_Provincia=$fk_provincia";		
		$rs=$dbm->getSQL($query);			
		if($rs)
		{	return $rs;
		}
		
	}
	
	function Generar_Combo_Distritos($idDepartamento, $idProvincia)
	{ $rs=$this->ListarDistritos($idDepartamento, $idProvincia);
		if (mysql_num_rows($rs)>0)
			{	echo "<select id='distrito'>";				
	 			while($data=mysql_fetch_array($rs,MYSQL_NUM))
				{	echo  "<option> $data[1] </option>";			
				}
				echo "</select>";
 			}	
		else
			{	echo "no existen datos para mostrar";
			}
		mysql_free_result($rs);	
	}

	
	function Ubicacion_Evento($idEvento)
	{	
		$dbm=new ManejaBD;
		$query="SELECT direccion FROM Ubicacion where fk_Evento=$idEvento";		
		$rs=$dbm->getSQL($query);			
		if($rs)
		{	return $rs;
		}
		
	}
	
	
}

A pedido de un usuario ahi esta cargar_distritos.php

 
 
	include("../cls/clsManejaBD.php"); 
	include("../cls/clsUbicacion.php"); 
	$id_departamento=$_GET['idDep'];
	$id_Provincia=$_GET['idProv'];
	$u=new Ubicacion(); $u->Generar_Combo_Distritos($id_departamento,$id_Provincia);
 

aunque un poco largo espero sea entendible _

Ejecutar una función del Padre

Codigo en JavaScript para ejecutar una función de una Página padre al momento de cerrar la ventana hijo
 
  window.opener.parent.funcionDePadre();
  window.close();
 

Comprobar si una variable ha sido declarada

No lo he testeado mucho, lo acabo de encontrar por ahí.

function isDefined(sVarName)
{
    return (typeof(window[sVarName]) == "undefined") ? false : true;
}

Redireccion en cierto tiempo

Para poder tener una redireccion en cierto tiempo en una pagina, podemos incrustar esto en la cabecera de nuestra pagina.
 
    var pagina = 'http://www.tiexo.com';
    var segundos = 5;
    function redireccion() {
        document.location.href=pagina;
    }
    setTimeout("redireccion()",segundos);
 
Oh! y juanjo me dice que tambien se hace de esta forma, creo que es mas optimo!
 
     <META HTTP-EQUIV="Refresh" CONTENT="5; URL=http://www.tiexo.com">
 
Gracias Juanjo

Validar una Forma con Javascript

Con esto podremos validar una forma en Javascript lo pongo de forma rapida, despues le pongo mas formato y explicacion, disculpen las molestias
 
    function validate(nombreForma) {
    var theMessage = "Please complete the following:\n-----------------------------------\n";
    var noErrors = theMessage
 
    // No vacio
    if (document.nombreForma.name.value=="") {
    theMessage = theMessage + "\n --> Your name";
    }
 
    // Validar un correo electronico
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(document.form1.email.value)){
    theMessage = theMessage + "\n --> Enter a valid e-mail address";
    }
 
    // Entrada de cierta cantidad de letras
    var lengthCheck = document.nombreForma.code.value
    if (lengthCheck.length < 4) {
    theMessage = theMessage + "\n --> Enter 4 character code";
    }
 
    // radio button seleccionado
    var radioCheck = false;
    for (i = 0; i < document.nombreForma.gender.length; i++) {
    if (document.nombreForma.gender[i].checked)
    radioCheck = true; }
    if (!radioCheck) {
    theMessage = theMessage + "\n --> Choose your gender";
    }
 
    // Al menos un check box
    var multiCheckbox = false;
    for (i = 0; i < document.nombreForma.session.length; i++) {
    if (document.nombreForma.session[i].checked)
    multiCheckbox = true; }
    if (!multiCheckbox) {
    theMessage = theMessage + "\n --> Choose which session(s)";
    }
 
    // Select List Usar
    var listCheck = document.form1.location.selectedIndex;
    if (document.nombreForma.location.options[listCheck].value=="none") {
    theMessage = theMessage + "\n --> Choose a location";
    }
 
    // Checkbox Activado
    var boxCheck = false;
    if (document.nombreForma.confirm.checked) {
    boxCheck = true; }
    if (!boxCheck) {
    theMessage = theMessage + "\n --> Agree to the terms";
    }
 
    // No hubo errores
    if (theMessage == noErrors) {
    return true;
 
    } else {
 
    // Errores encontrados
    alert(theMessage);
    return false;
    }
}
 

Cambiar estilos dinámicamente con cookie

El siguiente recorte explica como se puede cambiar el estilo de una página web dinámicamente y recordar la preferencia del usuario al salir de la página guardando en una cookie dicho estilo.
Para ello hay que tener varios estilos css y unas imagenes que corresponden al color básico de dicho estilo.

Para cambiar dinámicamente el estilo y poder guardar la cookie se utiliza un javascript bastante conocido llamado styleswitcher.js
 
  function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}
 
function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}
 
function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}
 
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
 
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
 
function leerEstilo() {
  var cookie = readCookie("style");
  var title;
  if(cookie == null){
  	title = "verde";	
  } else {
  	title = cookie ? cookie : getPreferredStyleSheet();
  }
  setActiveStyleSheet(title);
}
 
function guardarEstilo() {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}
 
En el head de nuestro HTML escribimos las siguientes sentencias para utilizar dicho javascript y nuestros css:


<!-- declaración de estilos css -->
<link rel="stylesheet" type="text/css" href="estilos/verde.css" title="verde">
<link rel="alternate stylesheet" type="text/css" href="estilos/azul.css" title="azul">
<link rel="alternate stylesheet" type="text/css" href="estilos/rojo.css" title="rojo">
<link rel="alternate stylesheet" type="text/css" href="estilos/amarillo.css" title="amarillo">
<link rel="alternate stylesheet" type="text/css" href="estilos/gris.css" title="gris">
<link rel="alternate stylesheet" type="text/css" href="estilos/marron.css" title="marron">
<link rel="alternate stylesheet" type="text/css" href="estilos/lila.css" title="lila">
<link rel="alternate stylesheet" type="text/css" href="estilos/naranja.css" title="naranja">
<!-- fin declaración estilos css -->

<!-- declaración de ficheros javascript -->
<script type="text/javascript" src="javascript/styleswitcher.js"></script>
<!-- fin declaración de ficheros javascript -->
Con el atributo rel="stylesheet" indicamos cual es el estilo por defecto y con rel="alternate stylesheet" cuales son los estilos alternativos. Hay que añadir un title para identificar el estilo y poder guardarlo en la cookie.

A continuación nos creamos el div que contendrá las imagenes que al pulsarse cambiarán el estilo:

<table class="tabla2" cellspacing=0 cellpadding=0 width=136 border=0>
    <tbody>
        <tr>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('verde', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/verde.jpg" width=26px height=26px alt="verde" title="verde"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('rojo', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/rojo.jpg" width=26px height=26px alt="rojo" title="rojo"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('azul', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/azul.jpg" width=26px height=26px alt="azul" title="azul"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('marron', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/marron.jpg" width=26px height=26px alt="marron" title="marron"></a>
            </td>
        </tr>
        <tr>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('lila', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/lila.jpg" width=26px height=26px alt="lila" title="lila"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('naranja', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/naranja.jpg" width=26px height=26px alt="naranja" title="naranja"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('amarillo', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/amarillo.jpg" width=26px height=26px alt="amarillo" title="amarillo"></a>
            </td>
            <td valign=top class="color00f" align=middle>
                <a href="#" onclick="setActiveStyleSheet('gris', 1); return false; actualizar();" style="text-decoration: none">
                <img src="imagenes/estilos/gris.jpg" width=26px height=26px alt="gris" title="gris"></a>
            </td>
        </tr>
    </tbody>
</table>
Al hacer click sobre la imagen se llama a la función javascript setActiveStyleSheet(estilo, 1); que activa dicho estilo y con la función actualizar(); se actualiza la página para mostrarla con el nuevo estilo.

Para que al salir de la página HTML se guarde en una cookie el valor del último estilo pulsado hay que introducir el siguiente código en la etiqueta <body>


<body onLoad="leerEstilo();" onunload="guardarEstilo();">
Estas llamadas en el body hacen que cuando se cargue la página se lea la cookie y se active el estilo que contiene dicha cookie y que al cerrar la página se lea el estilo y se guarde en una cookie.

Div con efecto de desvanecimiento

La clase Fadomatic nos permite implementar efectos de opacidad con facilidad. Es soportado por múltiples navegadores y nos permite permutar la opacidad de elementos.
La sintaxis de la función es la siguiente:
 
  function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity)
 
Donde:element - Es el elemento con el que vamos a jugar rate- La velocidad (de 0 a 100)initialOpacity (opcional, predeterminado 100) - La opacidad de inicio del elemento (de 0 a 100)minOpacity (opcional, predeterminado 0) - La opacidad minima del elemento (de 0 a 100)maxOpacity (opcional, predeterminado 0) - La opacidad máxima del elemento (de 0 a 100)
Existen 6 métodos a utiliza con el objeto Fadomatic:fadeOut() - Transición hacia transparentefadeIn() - Transición hacia opaco haltFade() - Detiene la transición en cursoresumeFade() - Reanuda la transición en cursoshow() - Establece la opacidad del elemento al valor máximohide() -Hace el elemento transparente.

Ejemplo de uso:

1.- Lo primero que tenemos que hacer es descargar el script Fadomatic desde su sitio web o copiarnos el siguiente código en un archivo .js:
 
// Fade interval in milliseconds
// Make this larger if you experience performance issues
Fadomatic.INTERVAL_MILLIS = 50;
 
// Creates a fader
// element - The element to fade
// speed - The speed to fade at, from 0.0 to 100.0
// initialOpacity (optional, default 100) - element's starting opacity, 0 to 100
// minOpacity (optional, default 0) - element's minimum opacity, 0 to 100
// maxOpacity (optional, default 0) - element's minimum opacity, 0 to 100
function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) {
  this._element = element;
  this._intervalId = null;
  this._rate = rate;
  this._isFadeOut = true;
 
  // Set initial opacity and bounds
  // NB use 99 instead of 100 to avoid flicker at start of fade
  this._minOpacity = 0;
  this._maxOpacity = 99;
  this._opacity = 99;
 
  if (typeof minOpacity != 'undefined') {
    if (minOpacity < 0) {
      this._minOpacity = 0;
    } else if (minOpacity > 99) {
      this._minOpacity = 99;
    } else {
      this._minOpacity = minOpacity;
    }
  }
 
  if (typeof maxOpacity != 'undefined') {
    if (maxOpacity < 0) {
      this._maxOpacity = 0;
    } else if (maxOpacity > 99) {
      this._maxOpacity = 99;
    } else {
      this._maxOpacity = maxOpacity;
    }
 
    if (this._maxOpacity < this._minOpacity) {
      this._maxOpacity = this._minOpacity;
    }
  }
  
  if (typeof initialOpacity != 'undefined') {
    if (initialOpacity > this._maxOpacity) {
      this._opacity = this._maxOpacity;
    } else if (initialOpacity < this._minOpacity) {
      this._opacity = this._minOpacity;
    } else {
      this._opacity = initialOpacity;
    }
  }
 
  // See if we're using W3C opacity, MSIE filter, or just
  // toggling visiblity
  if(typeof element.style.opacity != 'undefined') {
 
    this._updateOpacity = this._updateOpacityW3c;
 
  } else if(typeof element.style.filter != 'undefined') {
 
    // If there's not an alpha filter on the element already,
    // add one
    if (element.style.filter.indexOf("alpha") == -1) {
 
      // Attempt to preserve existing filters
      var existingFilters="";
      if (element.style.filter) {
        existingFilters = element.style.filter+" ";
      }
      element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")";
    }
 
    this._updateOpacity = this._updateOpacityMSIE;
    
  } else {
 
    this._updateOpacity = this._updateVisibility;
  }
 
  this._updateOpacity();
}
 
// Initiates a fade out
Fadomatic.prototype.fadeOut = function () {
  this._isFadeOut = true;
  this._beginFade();
}
 
// Initiates a fade in
Fadomatic.prototype.fadeIn = function () {
  this._isFadeOut = false;
  this._beginFade();
}
 
// Makes the element completely opaque, stops any fade in progress
Fadomatic.prototype.show = function () {
  this.haltFade();
  this._opacity = this._maxOpacity;
  this._updateOpacity();
}
 
// Makes the element completely transparent, stops any fade in progress
Fadomatic.prototype.hide = function () {
  this.haltFade();
  this._opacity = 0;
  this._updateOpacity();
}
 
// Halts any fade in progress
Fadomatic.prototype.haltFade = function () {
 
  clearInterval(this._intervalId);
}
 
// Resumes a fade where it was halted
Fadomatic.prototype.resumeFade = function () {
 
  this._beginFade();
}
 
// Pseudo-private members
 
Fadomatic.prototype._beginFade = function () {
 
  this.haltFade();
  var objref = this;
  this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS);
}
 
Fadomatic.prototype._tickFade = function () {
 
  if (this._isFadeOut) {
    this._opacity -= this._rate;
    if (this._opacity < this._minOpacity) {
      this._opacity = this._minOpacity;
      this.haltFade();
    }
  } else {
    this._opacity += this._rate;
    if (this._opacity > this._maxOpacity ) {
      this._opacity = this._maxOpacity;
      this.haltFade();
    }
  }
 
  this._updateOpacity();
}
 
Fadomatic.prototype._updateVisibility = function () {
  
  if (this._opacity > 0) {
    this._element.style.visibility = 'visible';
  } else {
    this._element.style.visibility = 'hidden';
  }
}
 
Fadomatic.prototype._updateOpacityW3c = function () {
  
  this._element.style.opacity = this._opacity/100;
  this._updateVisibility();
}
 
Fadomatic.prototype._updateOpacityMSIE = function () {
  
  this._element.filters.alpha.opacity = this._opacity;
  this._updateVisibility();
}
 
Fadomatic.prototype._updateOpacity = null;
 
2.- Incluimos una llamada al script donde lo deseemos utilizar:

<script type="text/javascript" language="JavaScript" src="fadomatic-1_2.js"></script>
Incluimos el siguiente CSS:
 
#caja_fadomatic { width: 150px; height:110px; background-color:#990000; padding:4px; color:#FFFFFF; font:10px Verdana, Arial, Helvetica, sans-serif }
 
Y por último:

<div id="caja_fadomatic"> Caja </div> <p>
<a href="javascript:fader.fadeOut();">Ocultar</a> 
<a href="javascript:fader.fadeIn();">Mostrar</a><br> <br> </p> 
<script language="javascript"> var fader = new Fadomatic(caja_fadomatic, 5, 100); </script>
info@recortex.com - Proyecto: Juanjo Navarro, 2006 - Diseño: Albin