Sie sind auf Seite 1von 16

<!-- Consigue mas JavaScript en http://www.mundojavascript.com --> <!-- Original Author unknown --> <SCRIPT language=JavaScript> dCol='ffffff';//date colour.

fCol='00ffff';//face colour. sCol='ffffff';//seconds colour. mCol='ccff00';//minutes colour. hCol='ffff00';//hours colour. ClockHeight=40; ClockWidth=40; ClockFromMouseY=0; ClockFromMouseX=100;

//Alter nothing below! Alignments will be lost!

d=new Array("DOMINGO","LUNES","MARTES","MIERCOLES","JUEVES","VIERNES","SABADO"); m=new Array("ENERO","FEBRERO","MARZO","ABRIL","MAYO","JUNIO","JULIO","AGOSTO","SEPTIEMBRE", "OCTUBRE","NOVIEMBRE","DICIEMBRE"); date=new Date(); day=date.getDate(); year=date.getYear(); if (year < 2000) year=year+1900; TodaysDate=" "+d[date.getDay()]+" "+day+" "+m[date.getMonth()]+" "+year; D=TodaysDate.split('');

H='...'; H=H.split(''); M='....'; M=M.split(''); S='.....'; S=S.split(''); Face='1 2 3 4 5 6 7 8 9 10 11 12'; font='Arial'; size=1; speed=0.6; ns=(document.layers); ie=(document.all); Face=Face.split(' '); n=Face.length; a=size*10; ymouse=0; xmouse=0; scrll=0; props="<font face="+font+" size="+size+" color="+fCol+"><B>"; props2="<font face="+font+" size="+size+" color="+dCol+"><B>"; Split=360/n; Dsplit=360/D.length; HandHeight=ClockHeight/4.5 HandWidth=ClockWidth/4.5 HandY=-7; HandX=-2.5;

scrll=0; step=0.06; currStep=0; y=new Array();x=new Array();Y=new Array();X=new Array(); for (i=0; i < n; i++){y[i]=0;x[i]=0;Y[i]=0;X[i]=0} Dy=new Array();Dx=new Array();DY=new Array();DX=new Array(); for (i=0; i < D.length; i++){Dy[i]=0;Dx[i]=0;DY[i]=0;DX[i]=0} if (ns){ for (i=0; i < D.length; i++) document.write('<layer name="nsDate'+i+'" top=0 left=0 height='+a+' width='+a+'><center>'+props2+D[i]+'</font></center></layer>'); for (i=0; i < n; i++) document.write('<layer name="nsFace'+i+'" top=0 left=0 height='+a+' width='+a+'><center>'+props+Face[i]+'</font></center></layer>'); for (i=0; i < S.length; i++) document.write('<layer name=nsSeconds'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+sCol+'><center><b>'+S[i]+'</b></center></font></layer>'); for (i=0; i < M.length; i++) document.write('<layer name=nsMinutes'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+mCol+'><center><b>'+M[i]+'</b></center></font></layer>'); for (i=0; i < H.length; i++) document.write('<layer name=nsHours'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+hCol+'><center><b>'+H[i]+'</b></center></font></layer>'); } if (ie){ document.write('<div id="Od" style="position:absolute;top:0px;left:0px"><div style="position:relative">'); for (i=0; i < D.length; i++)

document.write('<div id="ieDate" style="position:absolute;top:0px;left:0;height:'+a+';width:'+a+';textalign:center">'+props2+D[i]+'</B></font></div>'); document.write('</div></div>'); document.write('<div id="Of" style="position:absolute;top:0px;left:0px"><div style="position:relative">'); for (i=0; i < n; i++) document.write('<div id="ieFace" style="position:absolute;top:0px;left:0;height:'+a+';width:'+a+';textalign:center">'+props+Face[i]+'</B></font></div>'); document.write('</div></div>'); document.write('<div id="Oh" style="position:absolute;top:0px;left:0px"><div style="position:relative">'); for (i=0; i < H.length; i++) document.write('<div id="ieHours" style="position:absolute;width:16px;height:16px;fontfamily:Arial;font-size:16px;color:'+hCol+';text-align:center;font-weight:bold">'+H[i]+'</div>'); document.write('</div></div>'); document.write('<div id="Om" style="position:absolute;top:0px;left:0px"><div style="position:relative">'); for (i=0; i < M.length; i++) document.write('<div id="ieMinutes" style="position:absolute;width:16px;height:16px;fontfamily:Arial;font-size:16px;color:'+mCol+';text-align:center;font-weight:bold">'+M[i]+'</div>'); document.write('</div></div>') document.write('<div id="Os" style="position:absolute;top:0px;left:0px"><div style="position:relative">'); for (i=0; i < S.length; i++) document.write('<div id="ieSeconds" style="position:absolute;width:16px;height:16px;fontfamily:Arial;font-size:16px;color:'+sCol+';text-align:center;font-weight:bold">'+S[i]+'</div>'); document.write('</div></div>') }

(ns)?window.captureEvents(Event.MOUSEMOVE):0; function Mouse(evnt){ ymouse = (ns)?evnt.pageY+ClockFromMouseY-(window.pageYOffset):event.y+ClockFromMouseY; xmouse = (ns)?evnt.pageX+ClockFromMouseX:event.x+ClockFromMouseX; } (ns)?window.onMouseMove=Mouse:document.onmousemove=Mouse; function ClockAndAssign(){ time = new Date (); secs = time.getSeconds(); sec = -1.57 + Math.PI * secs/30; mins = time.getMinutes(); min = -1.57 + Math.PI * mins/30; hr = time.getHours(); hrs = -1.575 + Math.PI * hr/6+Math.PI*parseInt(time.getMinutes())/360; if (ie){ Od.style.top=window.document.body.scrollTop; Of.style.top=window.document.body.scrollTop; Oh.style.top=window.document.body.scrollTop; Om.style.top=window.document.body.scrollTop; Os.style.top=window.document.body.scrollTop; } for (i=0; i < n; i++){ var F=(ns)?document.layers['nsFace'+i]:ieFace[i].style; F.top=y[i] + ClockHeight*Math.sin(-1.0471 + i*Split*Math.PI/180)+scrll; F.left=x[i] + ClockWidth*Math.cos(-1.0471 + i*Split*Math.PI/180); }

for (i=0; i < H.length; i++){ var HL=(ns)?document.layers['nsHours'+i]:ieHours[i].style; HL.top=y[i]+HandY+(i*HandHeight)*Math.sin(hrs)+scrll; HL.left=x[i]+HandX+(i*HandWidth)*Math.cos(hrs); } for (i=0; i < M.length; i++){ var ML=(ns)?document.layers['nsMinutes'+i]:ieMinutes[i].style; ML.top=y[i]+HandY+(i*HandHeight)*Math.sin(min)+scrll; ML.left=x[i]+HandX+(i*HandWidth)*Math.cos(min); } for (i=0; i < S.length; i++){ var SL=(ns)?document.layers['nsSeconds'+i]:ieSeconds[i].style; SL.top=y[i]+HandY+(i*HandHeight)*Math.sin(sec)+scrll; SL.left=x[i]+HandX+(i*HandWidth)*Math.cos(sec); } for (i=0; i < D.length; i++){ var DL=(ns)?document.layers['nsDate'+i]:ieDate[i].style; DL.top=Dy[i] + ClockHeight*1.5*Math.sin(currStep+i*Dsplit*Math.PI/180)+scrll; DL.left=Dx[i] + ClockWidth*1.5*Math.cos(currStep+i*Dsplit*Math.PI/180); } currStep-=step; } function Delay(){ scrll=(ns)?window.pageYOffset:0; Dy[0]=Math.round(DY[0]+=((ymouse)-DY[0])*speed); Dx[0]=Math.round(DX[0]+=((xmouse)-DX[0])*speed);

for (i=1; i < D.length; i++){ Dy[i]=Math.round(DY[i]+=(Dy[i-1]-DY[i])*speed); Dx[i]=Math.round(DX[i]+=(Dx[i-1]-DX[i])*speed); } y[0]=Math.round(Y[0]+=((ymouse)-Y[0])*speed); x[0]=Math.round(X[0]+=((xmouse)-X[0])*speed); for (i=1; i < n; i++){ y[i]=Math.round(Y[i]+=(y[i-1]-Y[i])*speed); x[i]=Math.round(X[i]+=(x[i-1]-X[i])*speed); } ClockAndAssign(); setTimeout('Delay()',20); } if (ns||ie)window.onload=Delay; </SCRIPT>

<SCRIPT> // Array de los meses var monthNames = new makeArray(12); monthNames[0] = "Enero"; monthNames[1] = "Febrero"; monthNames[2] = "Marzo"; monthNames[3] = "Abril"; monthNames[4] = "Mayo"; monthNames[5] = "Junio"; monthNames[6] = "Julio"; monthNames[7] = "Agosto"; monthNames[8] = "Septiembre"; monthNames[9] = "Octubre"; monthNames[10] = "Noviembre"; monthNames[11] = "Diciembre"; // Array de los das var dayNames = new makeArray(7); dayNames[0] = "Domingo"; dayNames[1] = "Lunes"; dayNames[2] = "Martes"; dayNames[3] = "Mi&eacute;rcoles"; dayNames[4] = "Jueves"; dayNames[5] = "Viernes"; dayNames[6] = "S&aacute;bado"; var now = new Date(); var year = now.getYear(); if (year < 2000) year = year + 1900; function makeArray(len) { for (var i = 0; i < len; i++) this[i] = null; this.length = len; } </SCRIPT>

<script language="JavaScript"> <!-document.write( dayNames[now.getDay()] + " " + now.getDate() + " de " + monthNames[now.getMonth()] + " " +" de " + year); // --> </script>

El siguiente script nos permite incorporan en una pgina la fecha y la hora actual, obtenida de la mquina del visitante. Fecha: 7/20/2010 Hora: 7:30 P.M.

Cdigo fuente:
Debs ubicar este script en cualquier parte de la pgina (dentro de las etiquetas BODY, por supuesto) donde quieras que aparezca la fecha y la hora:
<script LANGUAGE="JavaScript"> <!-- COMIENZO Stamp = new Date(); year = Stamp.getYear(); if (year < 2000) year = 1900 + year; document.write('<font size="2" face="Arial"><B>Fecha: ' + (Stamp.getMonth() + 1) +"/"+Stamp.getDate()+ "/"+ year + '</B></font><BR>'); var Hours; var Mins; var Time; Hours = Stamp.getHours(); if (Hours >= 12) { Time = " P.M."; } else { Time = " A.M."; } if (Hours > 12) { Hours -= 12; } if (Hours == 0) { Hours = 12; } Mins = Stamp.getMinutes(); if (Mins < 10) { Mins = "0" + Mins; } document.write('<font size="2" face="Arial"><B>Hora: ' + Hours + ":" + Mins + Time + '</B></font>'); // FIN --> </script>

Te mostramos cmo realizar un slide show de imgenes en secuencia una con otra encadenadas con un fundido negro. Para ello debemos ubicar el siguiente cdigo dentro de la cabecera (entre <head> y </head>):
<script language="JavaScript"> // Browser Slide-Show script. // With image cross fade effect for those browsers that support it. var slideCache = new Array(); function RunSlideShow(pictureName,imageFiles,displaySecs) { var imageSeparator = imageFiles.indexOf(";"); var nextImage = imageFiles.substring(0,imageSeparator); if (document.all) { document.getElementById(pictureName).style.filter="blendTrans(duration=2)"; document.getElementById(pictureName).filters.blendTrans.Apply(); } document.getElementById(pictureName).src = nextImage; if (document.all) { document.getElementById(pictureName).filters.blendTrans.Play(); } var futureImages= imageFiles.substring(imageSeparator+1,imageFiles.length) + ';' + nextImage; setTimeout("RunSlideShow('"+pictureName+"','"+futureImages+"',"+displaySecs+")", displaySecs*1000); // Cache the next image to improve performance. imageSeparator = futureImages.indexOf(";"); nextImage = futureImages.substring(0,imageSeparator); if (slideCache[nextImage] == null) { slideCache[nextImage] = new Image; slideCache[nextImage].src = nextImage; } } </script>

Y donde queramos ubicar el slide ubicamos las siguientes lneas:


<img border="1" src="foto1.jpg" width="271" height="250" id="Fotos"> <script language="JavaScript"> RunSlideShow("Fotos","foto1.jpg;foto2.jpg;foto3.jpg;foto4.jpg;" + "foto5.jpg",5); </script>

Ejemplo:

Muchos de nuestros usuarios nos consultaron sobre el script que vamos a mostrar hoy, se trata de un reloj digital que muestra la hora actual segundo a segundo. Lo primero que hay que hacer es copiar el siguiente javascript entre las etiquetas <head> y </head>:
<script language="javascript"> <!-- Se abre el comentario para ocultar el script de navegadores antiguos function muestraReloj() { // Compruebo si se puede ejecutar el script en el navegador del usuario if (!document.layers && !document.all && !document.getElementById) return; // Obtengo la hora actual y la divido en sus partes var fechacompleta = new Date(); var horas = fechacompleta.getHours(); var minutos = fechacompleta.getMinutes(); var segundos = fechacompleta.getSeconds(); var mt = "AM"; // Pongo el formato 12 horas if (horas > 12) { mt = "PM"; horas = horas - 12; } if (horas == 0) horas = 12; // Pongo minutos y segundos con dos dgitos if (minutos <= 9) minutos = "0" + minutos; if (segundos <= 9) segundos = "0" + segundos; // En la variable 'cadenareloj' puedes cambiar los colores y el tipo de fuente cadenareloj = "<font size='1' face='verdana' ><b>" + horas + ":" + minutos + ":" + segundos + " " + mt + "</b></font>"; // Escribo el reloj de una manera u otra, segn el navegador del usuario if (document.layers) { document.layers.spanreloj.document.write(cadenareloj); document.layers.spanreloj.document.close(); } else if (document.all) spanreloj.innerHTML = cadenareloj; else if (document.getElementById) document.getElementById("spanreloj").innerHTML = cadenareloj;

// Ejecuto la funcin con un intervalo de un segundo setTimeout("muestraReloj()", 1000); } // Fin del script --> </script>

Antes de insertar el reloj dentro de la pgina hay que agregar en el body la lnea OnLoad="muestraReloj()" para poder iniciarlo.
<body onLoad="muestraReloj()">

Y por ltimo insertamos el siguiente cdigo en donde queremos que se vea el reloj:
<span id="spanreloj" style="position:absolute;left:10;top:10;"></span>

En este artculo veremos cmo ejecutar cdigo ASP, PHP o de cualquier otro lenguaje dinmico interpretado en el servidor mediante una llamada JavaScript en un documento HTML comn y corriente. En el archivo HTML debemos ubicar la llamada al archivo que queremos ejecutar:
index.htm <HTML> <HEAD> <TITLE>Ejectuar cdigo PHP o ASP con JavaScript</TITLE> </HEAD> <BODY> <script language="JavaScript" src="archivo.php"></script> <script language="JavaScript" src="archivo.asp"></script> </BODY> </HTML>

El archivo del Script debe contener la funcion document.write al final del mismo para poder imprimir el contenido que gener dinmicamente:
archivo.php <? // En este espacio pondremos todo el // cdigo PHP que queremos ejecutar // y luego juntar todo lo que es

// necesario imprimir en una sola // variable. $variable = "Script PHP ejecutado desde una pgina HTML"; ?> document.write("<?=$variable;?>"); archivo.asp <% ' En este espacio pondremos todo el ' cdigo ASP que queremos ejecutar ' y luego juntar todo lo que es ' necesario imprimir en una sola ' variable. variable = "Script ASP ejecutado desde una pgina HTML" %> document.write("<%=variable%>");

En muchas ocasiones, cuando completamos un formulario y hacemos click sobre el botn "Enviar", observamos en el navegador que el proceso no avanza, y volvemos a hacer click sobre el botn. A raz de eso, la mayora de las veces el proceso se realiza nuevamente, creando un registro repetido en una base de datos o enviando dos emails. Una manera de evitarlo es utilizando un simple script que evita que se clickee ms de una vez sobre el botn de envo del formulario. Debemos ubicar el cdigo dentro de la cabecera de la pgina (entre <head> y </head>):
<script LANGUAGE="JavaScript"> <!-var cuenta=0; function enviado() { if (cuenta == 0) { cuenta++; return true; } else { alert("El formulario ya est siendo enviado, por favor aguarde un instante."); return false; } } // --> </script>

Y en el action del formulario debemos agregar lo marcado en negrita:


<form method="POST" action="proceso.php" onSubmit="return enviado()"> ... <input type="submit" value="Enviar"> </form>

Ejemplo:

Enviar formulario

(Al enviarlo se cargar nuevamente la pgina de esta artculo)

En un artculo anterior vimos como mostrar banners en forma aleatoria al cargar la pgina, en esta ocasin veremos como hacer lo mismo pero sin la necesidad de actualizar la pgina. Primero debemos colocar el siguiente JavaScript en la cabecera de la pgina (entre los tags <head> y </head>):
<SCRIPT LANGUAGE="JavaScript"> <!-- Begin var mfBanners = [ ['http://www.direccion1.com', 'imagen1.gif'], ['http://www.direccion2.com', 'imagen2.gif'] ]; var mfIe = false; if( document.all) { mfIe = true; } var mfBannerIndex = 0; function mfBannerChange() { var htmlString = '<a target="_blank" href="'+mfBanners[mfBannerIndex][0]+'"> <img border="0" src="'+mfBanners[mfBannerIndex][1]+'"></a>'; if( mfIe) { document.all.banner.innerHTML = htmlString; } else { document.layers["banner"].document.open(); document.layers["banner"].document.write( htmlString); document.layers["banner"].document.close(); } if(mfBannerIndex < mfBanners.length - 1) mfBannerIndex++; else mfBannerIndex = 0; } setInterval("mfBannerChange()", 5000); // End --> </script>

El siguiente paso es ubicar la siguiente lnea en el cuerpo de la pgina, en la parte donde queramos que roten los banners:
<div id="banner"></div>

Click aqu para ver el ejemplo funcionando

En otra ocasin mostramos este mismo script pero para mostrar banners de formato GIF en forma aleatoria. Nos ha llegado la duda de cmo mostrar banners aleatorios realizados en Flash, por lo que hemos adaptado el cdigo para poder hacerlo.

Funcionamiento
El JavaScript selecciona en forma aleatoria un nmero que va de 1 a la cantidad de banners que queremos mostrar. Luego realiza comparaciones con la sentencia IF para definir las variables que contendrn la informacin del banner: en este caso son flash con el nombre del archivo swf, y width y height con las medidas del mismo.
// En la variable "banner" definimos la cantidad de banners, en este caso sern 3 var banners = 3; ... // Definimos las propiedades del banner en cada posibilidad // Archivo SWF, ancho y alto. if (ad==1) { flash="banner1.swf" width="468"; height="60"; } if (ad==2) { flash="banner2.swf" width="468"; height="60"; } if (ad==3) { flash="banner3.swf" width="468"; height="60"; } ...

Por ltimo, deberemos imprimir el cdigo html para insertar el archivo Flash.

Cdigo completo
El siguiente JavaScript deber ser ubicado en la parte de la pgina que queremos que se muestre:
<SCRIPT LANGUAGE="JavaScript"> // Realizado por: Fabian Muller // WebExperto.com - Ayuda al webmaster en espaol // Comienzo var banners = 3; var ahora = new Date() var segundos = ahora.getSeconds() var ad = segundos % banners; ad +=1; if (ad==1) { flash="banner1.swf" width="468"; height="60"; } if (ad==2) { flash="banner2.swf" width="468"; height="60"; } if (ad==3) { flash="banner3.swf" width="468"; height="60"; } document.write('<center>'); document.write('<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=' + width + ' height=' + height + ' CODEBASE=\"http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0\">'); document.write('<PARAM NAME=\"MOVIE\" VALUE=\"' + flash + '\">'); document.write('<PARAM NAME=\"PLAY\" VALUE=\"true\">'); document.write('<PARAM NAME=\"LOOP\" VALUE=\"true\">'); document.write('<PARAM NAME=\"QUALITY\" VALUE=\"high\">'); document.write('<EMBED SRC=' + flash + ' width=' + width + ' height=' + height + ' PLAY=\"true\" LOOP=\"true\" QUALITY=\"high\" PLUGINSPAGE=\"http://www.macromedia.com/shockwave/download/index.cgi? P1_Prod_Version=ShockwaveFlash\">'); document.write('</EMBED>'); document.write('</OBJECT>'); document.write('</center>'); // Fin </SCRIPT>

Das könnte Ihnen auch gefallen