Foros del Web » Programando para Internet » Javascript »

FAQs JavaScript

Estas en el tema de FAQs JavaScript en el foro de Javascript en Foros del Web. P.- ¿Cómo puedo redireccionar una página a otra pasados unos segundos? R.- Con este código: Código PHP: < html > < head > </ head ...

  #91 (permalink)  
Antiguo 14/01/2003, 04:54
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
91. Redireccionar página pasados unos segundos

P.- ¿Cómo puedo redireccionar una página a otra pasados unos segundos?
R.- Con este código:

Código PHP:
<html>
<
head>

</
head>

<
body style="font:bold 10px/15px verdana;color:navy">
<
script>
//Script original de KarlanKas para forosdelweb.com


var segundos=3
var direccion='http://www.webareyou.com'
var mensaje="Nos hemos trasladado."

milisegundos=segundos*1000
window
.setTimeout("window.location.replace(direccion);",milisegundos);
document.write(mensaje+"  Si pasados "+segundos" segundos no es redireccionado pinche <a href='"+direccion+"'>aquí</a>.");
</script>

</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:38
  #92 (permalink)  
Antiguo 14/01/2003, 16:42
 
Fecha de Ingreso: febrero-2002
Ubicación: Navarra
Mensajes: 701
Antigüedad: 22 años, 1 mes
Puntos: 2
92 - Impedir que seleccionen mas de dos checkbox

P: Impedir que seleccionen mas de dos checkbox en un formulario

R:

Código PHP:

<script>

function 
countChoices(obj) {
max 1// max. number allowed at a time

obj.form.PollVote1.checked// your checkboxes here
obj.form.PollVote2.checked;

// add more if necessary

count = (0) + (0);
// If you have more checkboxes on your form
// add more (box_ ? 1 : 0) 's separated by '+'

if (count max) {
alert("Atencion! Solo puede seleccionar " max " opcion! \Quite una de ellas si quiere seleccionar otra.");
obj.checked false;
}
}


</script>

Y el campo checkbox es de la forma

<form name="form">

<input type="checkbox" value="1" name="PollVote1" onClick="countChoices(this)">

<input type="checkbox" value="2" name="PollVote2" onClick="countChoices(this)">

<form>

Si tienes los campos de esta forma (gracias tunait):

<form name="form">

<input type="checkbox" value="1" name="PollVote" onClick="countChoices(this)">

<input type="checkbox" value="2" name="PollVote" onClick="countChoices(this)">

<form>


deberás poner:

a = obj.form.PollVote[1].checked; // your checkboxes here
b = obj.form.PollVote[2].checked; 
Un saludo

Última edición por haven; 15/01/2003 a las 04:00
  #93 (permalink)  
Antiguo 15/01/2003, 14:55
Avatar de DanielRey
Usuario no validado
 
Fecha de Ingreso: enero-2001
Ubicación: Mendoza
Mensajes: 630
Antigüedad: 23 años, 2 meses
Puntos: 1
93 - Copiar el texto seleccionado

P: Copiar el texto que se ha seleccionado en la página.

R:
Código:
<!-- TWO STEPS TO INSTALL COPY SELECTED TEXT:

  1.  Copy the coding into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Raul Macias ([email protected] ) -->
<!-- Web Site:  http://members.cox.net/raulhmacias/ -->
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function copyit(theField) {
	var selectedText = document.selection;
	if (selectedText.type == 'Text') {
		var newRange = selectedText.createRange();
		theField.focus();
		theField.value = newRange.text;
	} else {
		alert('select a text in the page and then press this button');
	}
}
//  End -->
</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Raul Macias ([email protected] ) -->
<!-- Web Site:  http://members.cox.net/raulhmacias/ -->
<form name="it">

<p>This script allows you to select text on a web page and then copy it into a text box. Neat!</p>
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>

<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  1.69 KB -->

Última edición por DanielRey; 05/02/2003 a las 06:54
  #94 (permalink)  
Antiguo 29/01/2003, 22:17
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
94.- Tipo y versión del navegador

P: ¿Como puedo saber el tipo de navegador y la versión del mismo?

R: [ver ejemplo]

La función getBrowserName() retornará uno de los siguientes valores:
- ie = Internet Explorer
- ns = Netscape
- op = Opera
- mo = Mozilla

La función getBrowserVersion() retornará la versión del navegador correspondiente.

Código PHP:
<html>
 <
head>
  <
script LANGUAGE="JavaScript">

   var 
sBrowser;
   var 
sVersion;

   function 
setBrowserType(){
    var 
aBrowFull = new Array("opera""msie""netscape""gecko""mozilla");
    var 
aBrowVers = new Array("opera""msie""netscape""rv",    "mozilla"   );
    var 
aBrowAbrv = new Array("op",    "ie",   "ns",       "mo",    "ns"   );
    var 
sInfo navigator.userAgent.toLowerCase();;

    
sBrowser "";
    for (var 
0aBrowFull.lengthi++){
     if ((
sBrowser == "") && (sInfo.indexOf(aBrowFull[i]) != -1)){
      
sBrowser aBrowAbrv[i];
      
sVersion String(parseFloat(sInfo.substr(sInfo.indexOf(aBrowVers[i]) + aBrowVers[i].length 1)));
     }
    }
   }

   
setBrowserType();

   function 
getBrowserName(){
    return 
sBrowser;
   }

   function 
getBrowserVersion(){
    return 
sVersion;
   }

  
</script>
 </head>
 <body>
  <script language="JavaScript">
   setBrowserType();
   document.write("Browser: " + getBrowserName() + "<br>");
   document.write("Versión: " + getBrowserVersion() + "<br><br>" );
  </script>
 </body>
</html> 
Por favor, cualquier observación sobre este script o cualquier reporte de uso, incluirlo en este mensaje.

Última edición por Kaopectate; 31/01/2003 a las 23:11
  #95 (permalink)  
Antiguo 30/01/2003, 02:41
Avatar de epa2  
Fecha de Ingreso: abril-2002
Ubicación: Málaga
Mensajes: 1.475
Antigüedad: 21 años, 11 meses
Puntos: 9
95.- Buscador Web en mi sitio

P: ¿Como pongo un buscador Web en mi sitio?

R: Con este código.

Creditos: No me acuerdo de donde lo bajé pero ahí pongo el autor. / Script by Jari Aarniala [www.mbnet.fi/~foo -- [email protected]]

Ver ejemplo: Pulsa aqui pecadoooorr

NOTA: Si este script estuviese repe, favor de hacermelo saber. Gracias.

Código:
<body>
<tr>
    <td width="100%">
    <p align="center">&nbsp;</td>
</tr>
<tr>
    <td width="100%">&nbsp;</td>
  </tr>
  <tr>
    <td width="100%" style="text-indent: 0" height="19">
    <span lang="es"><script language="JavaScript">
<!--

//
// Script by Jari Aarniala [www.mbnet.fi/~foo -- [email protected]]
//
// This script makes it easy to choose with which search engine
// you`d like to search the net. You may use this if you keep this
// text here...
//

function startSearch(){
searchString = document.searchForm.searchText.value; 
if(searchString != ""){
searchEngine = document.searchForm.whichEngine.selectedIndex + 1;
finalSearchString = "";

if(searchEngine == 1){
finalSearchString = "http://www.altavista.digital.com/cgi-bin/query?pg=q&what=web&fmt=.&q=" + searchString;
}
if(searchEngine == 2){
finalSearchString = "http://av.yahoo.com/bin/query?p=" + searchString + "&hc=0&hs=0";
}
if(searchEngine == 3){
finalSearchString = "http://www.excite.com/search.gw?trace=a&search=" + searchString;
}
if(searchEngine == 4){
finalSearchString = "http://www.hotbot.com/?SW=web&SM=MC&MT=" + searchString + "&DC=10&DE=2&RG=NA&_v=2&act.search.x=89&act.search.y=7";
}
if(searchEngine == 5){
finalSearchString = "http://www.infoseek.com/Titles?qt=" + searchString + "&col=WW&sv=IS&lk=noframes&nh=10";
}
if(searchEngine == 6){
finalSearchString = "http://www.lycos.com/cgi-bin/pursuit?adv=%26adv%3B&cat=lycos&matchmode=and&query=" + searchString + "&x=45&y=11";
}
if(searchEngine == 7){
finalSearchString = "http://netfind.aol.com/search.gw?search=" + searchString + "&c=web&lk=excite_netfind_us&src=1";
}

location.href = finalSearchString;
}
}


// -->
    </script>

<basefont face="Verdana, Arial, sans-serif">

</span>

<form name="searchForm">

<div align="center">
  <center>

<table width=323 border="2" cellpadding=3 cellspacing=0 bgcolor=444444 style="border-collapse: collapse" bordercolor="#111111">

<tr>
<td bgcolor=lightblue width="148"><font size="1"><span lang="es">Buscar por:</span></font><font size=1 face="Verdana, Arial, sans-serif"><span lang="es"><br>

</span>
<td bgcolor=lightblue width="96"><font size="1"><span lang="es">Buscar desde:</span></font><span lang="es"><td bgcolor=lightblue width="90"> 

<tr>
<td bgcolor=navajowhite width="148">
<input style="background: dddddd" name="searchText" type="text" size="20">
<td bgcolor=navajowhite width="96">
<select style="background: dddddd" name="whichEngine">
<option selected>Altavista
<option>Yahoo!
<option>Excite
<option>Hotbot
<option>Infoseek
<option>Lycos
<option>AOL Netfind
</select>
<td bgcolor=navajowhite width="90">
<input type="button" value="Buscar " onClick="startSearch()">

</select>
</table>
  </center>
</div>
</form>

</span>&nbsp;</td>
  </tr>
</body>
</html>
__________________

***Aprendiz de todo y maestro de nada***
  #96 (permalink)  
Antiguo 31/01/2003, 11:40
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 1 mes
Puntos: 772
96.- Quitar recuadro punteado de enlace

P: ¿Como puedo quitar el recuadro de puntos de un enlace activo?

R: Con este código.

Creditos: unKnown, con modificación de Caricatos para que funcione también en Netscape.
Código PHP:
<html>
<
head>
<
script language="JavaScript">
    function 
prende() {
    
anclas=document.getElementsByTagName("a").length;
    for (
i=0;i<anclas;i++)
    
document.getElementsByTagName("a").item(i).onfocus=new Function("if(this.blur)this.blur()")
    }
</script>
</head>

<body onLoad="prende()">
<a href="#">Enlace1</a> <a href="#">Enlace2</a> <a href="#">Enlace3</a> 
</body>
</html> 

Última edición por JavierB; 15/03/2003 a las 04:52
  #97 (permalink)  
Antiguo 01/02/2003, 22:20
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
97.- Impedir que lean el código fuente

P: ¿Como puedo impedir que lean el código de mi página?

Créditos: itatpc

R: Independientemente de mi posición ante la idea de programar para que otros no lean, publico esta solución que sin lugar a dudas es una "pregunta frecuente". El hilo original fué publicado por itatpc y en él se discuten algunas posibilidades adicionales de seguridad.

Añadir esta línea en alguna parte de la cabecera:

Código PHP:
<frame>
<
noframes>
</
frame>
</
noframes
NOTA: Yanix comenta lo siguiente:
Cita:
Recuerden que solamente sirve si graban la pagina como web page completa (la cual te graba los css, javascripts, etc).
Si le cambian el tipo al momento de guardarla a Web HTML only, ese snip no va a funcionar. (probado en IE 5.5)

Última edición por Kaopectate; 15/04/2003 a las 14:27
  #98 (permalink)  
Antiguo 05/02/2003, 03:25
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
Mensaje 98 (comete un bizcocho). Evitar que vuelvan a la página anterior.

P.-¿Cómo conseguir que no funcione el botón atrás del navegador?
R.- Con este código, que debes poner en la página anterior, por lo que sólo podrás evitar que vuelva atrás si la página anterior es tuya.

Código PHP:
<script>
//Script original de KarlanKas para forosdelweb.com

// /////////////// EN EL HEAD ///////////////////

if (history.forward(1)){location.replace(history.forward(1))}

</script> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:39
  #99 (permalink)  
Antiguo 05/02/2003, 06:45
Avatar de DanielRey
Usuario no validado
 
Fecha de Ingreso: enero-2001
Ubicación: Mendoza
Mensajes: 630
Antigüedad: 23 años, 2 meses
Puntos: 1
99 - Poner texto vertical (sólo IE 5.0 +)

Poner texto vertical, al revés, rotarlo, que vuele, lo que quieras.

Para ver el original:
http://www.24fun.com/downloadcenter/...extwheel2.html
No te lo pierdas!!! es alucinante.

Código PHP:
<center>
<
OBJECT ID="pepe"
 
CLASSID="CLSID:369303C2-D7AC-11d0-89D5-00A0C90833E6"
 
STYLE="position:relative; width:300px; height:200 px">
        <
PARAM NAME="Line0001" VALUE="SetLineStyle(1)">
        <
PARAM NAME="Line0002" VALUE="SetLineColor(0,0,0)">
    <
PARAM NAME="Line0003" VALUE="SetFillColor(255,128,0)">
    <
PARAM NAME="Line0004" VALUE="SetFont('Arial', 20, 0, 0, 1, 0)">
    <
PARAM NAME="Line0005" VALUE="Text('Foros del Web', 0, 0, 0)">
    </
OBJECT>
<
script>
function 
eje1() {
  
pepe.Rotate(1500);
}

function 
eje2() {
  
pepe.Rotate(0150);
}

function 
eje3() {
  
pepe.Rotate(0015);
}
</script>
<input type=button onClick=eje1(); value="eje 1">
<input type=button onClick=eje2(); value="eje 2">
<input type=button onClick=eje3(); value="eje 3">
<!--
SetLineStyle(valor)
valor=0 => Sin línea de contorno de texto.
valor=1 => Línea continua
valor=2 => Linea discontinua

SetLineColor(R, G, B)
Intensidad del color (R=rojo, G=verde, B=azul)
de 0 a 255 de la linea de contorno de texto.

SetFillColor(R, G, B)
Intensidad del color (R=rojo, G=verde, B=azul)
del relleno del texto

SetFont('font', Tam, B, It, Sub, Tach)
font: Arial, Verdana, etcétera
Tam: El tamaño de la letra
B: 0=> Normal; 1=> Bold.
It: 0=> Normal; 1=> Itálica.
Sub: 0=> Normal; 1=> Subrayado
Tach: 0=> Normal; 1=> Tachado

Text('texto', H, V, R)
texto: El texto que se muestra
H: Posición horizontal inicial
V: Posición vertical inicial
R: Rotación plana inicial
--> 
  #100 (permalink)  
Antiguo 06/02/2003, 09:31
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
100.- Usos del método open()

P: ¿Que atributos puedo usar en el método open()?

R: El método open() tiene la siguiente sintaxis: [Ver wizard]

Código:
open(sURL, sNombre, sAtributos, bHistoria);
Donde:

sURL: Indica la dirección de la página a abrir.
sNombre: Nombre de la ventana (util para abrir una segunda dirección sobre la misma ventana.
sAtributos: Definidos posteriormente.
bHistoria: Si la nueva dirección se abre sobre una ventana existente, este indicador dice si debe o no añadirse al historial.

Lista de atributos utilizables en el método open (actualizada con indicadores de compatibilidad hasta NS-4 e IE-5).

Atributo: alwaysLowered (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería permanecer siempre al final de la pila de ventanas.

Atributo: alwaysRaised (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería permanecer siempre en el tope de la pila de ventanas.

Atributo: channelMode (IE-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica si la ventana deberá ser presentada en modo "Channel".

Atributo: dependent (NS-4)
Valor: Yes/No
Notas: Si una ventana es no dependiente, podrá sobrevivir luego de que su creador sea cerrado.

Atributo: directories (NS-4)
Valor: Yes/No
Notas: Controla la apariencia del toolbar personal de Netscape.

Atributo: fullscreen (IE-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Bajo Windows, MSIE llena la pantalla con la ventana.

Atributo: height (NS-2,IE-4)
Valor: Número.
Notas: Altura de la ventana.

Atributo: hotkeys (NS-4)
Valor: Yes/No
Notas: Colocando este valor a "no", deshabilitará la mayoría de los shortcuts de teclado aparte de la opción quit.

Atributo: innerHeight (NS-4)
Valor: Número.
Notas: Ajusta la altura interna de la ventana al valor dado.

Atributo: innerWidth (NS-4)
Valor: Número.
Notas: Ajusta el ancho interno de la ventana al valor dado.

Atributo: left (NS-4,IE-4)
Valor: Número.
Notas: Posición izquierda de la ventana.

Atributo: location (NS-2,IE-4)
Valor: Yes/No.
Notas: Barra de direcciones visible/invisible.

Atributo: menubar (NS-2)
Valor: Yes/No.
Notas: Barra de menú visible/invisible.

Atributo: outerHeight (NS-4)
Valor: Número.
Notas: Ajusta la altura externa de la ventana al valor dado.

Atributo: outerWidth (NS-4)
Valor: Número.
Notas: Ajusta el ancho externo de la ventana al valor dado.

Atributo: resizable (NS-2,IE-4)
Valor: Yes/No.
Notas: La ventana puede o no ser cambiada de tamaño.

Atributo: screenX (NS-4)
Valor: Número.
Notas: Nombre alterno para la posición izquierda de la ventana.

Atributo: screenY (NS-4)
Valor: Número.
Notas: Nombre alterno para la posición superior de la ventana.

Atributo: scrollbars (NS-2,IE-4)
Valor: Yes/No.
Notas: Pueden o no ser mostradas las barras de desplazamiento.

Atributo: status (NS-2,IE-4)
Valor: Yes/No.
Notas: Debe o no ser mostrada las barra de estado.

Atributo: toolbar (NS-2,IE-4)
Valor: Yes/No.
Notas: Debe o no ser mostrada las barra de herramientas.

Atributo: top (NS-4,IE-4)
Valor: Número.
Notas: Posición superior de la ventana.

Atributo: width (NS-2,IE-4)
Valor: Número.
Notas: Ancho de la ventana.

Atributo: z-lock (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería estar en una posición fija en la pila de ventanas.


Lanzando PopUps con JavaScript:

Si deseas conocer el modo correcto de abrir un popup usando JavaScript, te recomendamos este artículo (tomado de esta discusión). Creditos: ferent.


Algunos ejemplos frecuentes:

- Abrir una ventana en una ubicación específica:
open("ventana.htm", "nombre", "left=100,top=100,width=600,height=400");

- Abrir una ventana sin barra de herramientas, sin barra de dirección, sin barras de desplazamiento, sin barra de estatus:
open("ventana.htm", "nombre", "location=no,menubar=no,scrollbars=no,status=n o");

- Abrir una ventana fullscreen (solo Internet Explorer):
open("ventana.htm", "nombre", "fullscreen");

Para observaciones, actualizaciones o correcciones sobre este tema por favor ir al siguiente hilo.

Última edición por Kaopectate; 15/11/2004 a las 14:49
  #101 (permalink)  
Antiguo 06/02/2003, 10:36
Avatar de ferent  
Fecha de Ingreso: junio-2002
Ubicación: Madrid
Mensajes: 633
Antigüedad: 21 años, 9 meses
Puntos: 0
101 - Ordenar campos de una tabla segun columna

P. ¿Cómo puedo ordenar los datos de una tabla dependiendo de cada columna?
R. Muy sencillo, consta de dos pasos.

1º Añade este Script en el head
Código PHP:
<SCRIPT LANGUAGE="JavaScript">

<!-- 
Begin
function compare(sVal1sVal2){
//para cambiar el orden (ascendente o descendente) se debe 
//cambiar a negativo el primer 1 y a positivo el segundo, segun convenga
 
if (sVal1 sVal2) return 1;
 if (
sVal1 sVal2) return -1;
 return 
0;
}
function 
setDataType(cValue)
  {
    
// THIS FUNCTION CONVERTS DATES AND NUMBERS FOR PROPER ARRAY
    // SORTING WHEN IN THE SORT FUNCTION
    
var isDate = new Date(cValue);
    if (
isDate == "NaN")
      {
        if (
isNaN(cValue))
          {
            
// THE VALUE IS A STRING, MAKE ALL CHARACTERS IN
            // STRING UPPER CASE TO ASSURE PROPER A-Z SORT
            
cValue cValue.toUpperCase();
            return 
cValue;
          }
        else
          {
            
// VALUE IS A NUMBER, TO PREVENT STRING SORTING OF A NUMBER
            // ADD AN ADDITIONAL DIGIT THAT IS THE + TO THE LENGTH OF
            // THE NUMBER WHEN IT IS A STRING
            
var myNum;
            
myNum String.fromCharCode(48 cValue.length) + cValue;
            return 
myNum;
          }
        }
  else
      {
        
// VALUE TO SORT IS A DATE, REMOVE ALL OF THE PUNCTUATION AND
        // AND RETURN THE STRING NUMBER
        //BUG - STRING AND NOT NUMERICAL SORT .....
        // ( 1 - 10 - 11 - 2 - 3 - 4 - 41 - 5  etc.)
        
var myDate = new String();
        
myDate isDate.getFullYear() + " " ;
        
myDate myDate isDate.getMonth() + " ";
        
myDate myDate isDate.getDate(); + " ";
        
myDate myDate isDate.getHours(); + " ";
        
myDate myDate isDate.getMinutes(); + " ";
        
myDate myDate isDate.getSeconds();
        
//myDate = String.fromCharCode(48 + myDate.length) + myDate;
        
return myDate ;
      }
  }
function 
sortTable(coltableToSort)
  {
    var 
iCurCell col tableToSort.cols;
    var 
totalRows tableToSort.rows.length;
    var 
bSort 0;
    var 
colArray = new Array();
    var 
oldIndex = new Array();
    var 
indexArray = new Array();
    var 
bArray = new Array();
    var 
newRow;
    var 
newCell;
    var 
i;
    var 
c;
    var 
j;
    
// ** POPULATE THE ARRAY colArray WITH CONTENTS OF THE COLUMN SELECTED
    
for (i=1tableToSort.rows.lengthi++)
      {
        
colArray[1] = setDataType(tableToSort.cells(iCurCell).innerText);
        
iCurCell iCurCell tableToSort.cols;
      }
    
// ** COPY ARRAY FOR COMPARISON AFTER SORT
    
for (i=0colArray.lengthi++)
      {
        
bArray[i] = colArray[i];
      }
    
// ** SORT THE COLUMN ITEMS
    //alert ( colArray );
    
colArray.sort(compare);
    
//alert ( colArray );
    
for (i=0colArray.lengthi++)
      { 
// LOOP THROUGH THE NEW SORTED ARRAY
        
indexArray[i] = (i+1);
        for(
j=0bArray.lengthj++)
          { 
// LOOP THROUGH THE OLD ARRAY
            
if (colArray[i] == bArray[j])
              {  
// WHEN THE ITEM IN THE OLD AND NEW MATCH, PLACE THE
                // CURRENT ROW NUMBER IN THE PROPER POSITION IN THE
                // NEW ORDER ARRAY SO ROWS CAN BE MOVED ....
                // MAKE SURE CURRENT ROW NUMBER IS NOT ALREADY IN THE
                // NEW ORDER ARRAY
                
for (c=0c<ic++)
                  {
                    if ( 
oldIndex[c] == (j+1) )
                    {
                      
bSort 1;
                    }
                      }
                      if (
bSort == 0)
                        {
                          
oldIndex[i] = (j+1);
                        }
                          
bSort 0;
                        }
          }
    }
  
// ** SORTING COMPLETE, ADD NEW ROWS TO BASE OF TABLE ....
  
for (i=0i<oldIndex.lengthi++)
    {
      
newRow tableToSort.insertRow();
      for (
c=0c<tableToSort.colsc++)
        {
          
newCell newRow.insertCell();
          
newCell.innerHTML tableToSort.rows(oldIndex[i]).cells(c).innerHTML;
        }
      }
  
//MOVE NEW ROWS TO TOP OF TABLE ....
  
for (i=1i<totalRowsi++)
    {
      
tableToSort.moveRow((tableToSort.rows.length -1),1);
    }
  
//DELETE THE OLD ROWS FROM THE BOTTOM OF THE TABLE ....
  
for (i=1i<totalRowsi++)
    {
      
tableToSort.deleteRow();
    }
  }
//  End -->
</script> 
2º Paso: Crear la tabla

Código PHP:
//indicar el número de columnas, teniendo cuidado de que no haya colspan
<table name="rsTable" id="rsTable" cols=6>
<
tr><td><A href="java script:sortTable(0, rsTable">ID</A></td>
    <
td><A href="java script:sortTable(1, rsTable);">Nombre</A></td>
    <
td><A href="java script:sortTable(2, rsTable);">Apellidos</A></td>

//etc... 
Y lo demás depende de ustedes.
__________________
Culto es aquel que sabe donde encontrar lo que no sabe.
  #102 (permalink)  
Antiguo 06/02/2003, 11:26
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
102.- Extraer información de una opción seleccionada en un select

P: ¿Como puedo extraer de un elemento select el índice o el valor o el nombre desplegado en la opción seleccionada?

R:
Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   function 
cambia(){
    
with (document.frm){
     
indice.value String(selector.selectedIndex);
     
opcion.value selector.options[selector.selectedIndex].text;
     
valor.value selector.options[selector.selectedIndex].value;
    }
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   Indice:<input type="text" name="indice"><br>
   Opcion:<input type="text" name="opcion"><br>
   Valor: <input type="text" name="valor"><br>
   Seleccione:<select name="selector" onchange="cambia()">
    <option>Seleccione un valor</option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
   </select>
  </form>
 </body>
</html> 
  #103 (permalink)  
Antiguo 12/02/2003, 12:08
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
103. Una imagen linkable cada semana

P.- ¿Cómo puedo hacer que aparezca una imagen linkable nueva cada semana en mi web?

R.- Por medio de este código:

Código PHP:
<html>
<
head>

<
script>
//Script original de KarlanKas para Forosdelweb.com

var bisiesto=//Si es año bisiesto pon 1

enlace=new Array;
alt=new Array;
imagen=new Array;

//-------ENLACES ALT E IMAGEN PARA CADA SEMANA------------

enlace[1]="http://www.loslunesalsol.com/";
alt[1]="esta es la imagen del lunes"
imagen[1]="http://www.cartelia.net/fotos/l/loslunesalsol.jpg"

enlace[2]="http://www.martes.com";
alt[2]="esta es la imagen del martes";
imagen[2]="http://www.martes.com/images/marteshomesk.gif";

enlace[3]="http://www.wednesday.com";
alt[3]="Esta es la imagen del miércoles"
imagen[3]="http://www.wednesday.com/images/logo.gif";

enlace[4]="http://www.thursday.com/";
alt[4]="Es que en español no había..."
imagen[4]="http://www.thursday.com/5.jpg";

enlace[5]="http://www.tgifridays.com/index1.html";
alt[5]="No podía ser de otra forma!";
imagen[5]="http://www.tgifridays.com/index_files/newindex.gif";

enlace[6]="http://www.sabado.info";
alt[6]="Te gusta la música?";
imagen[6]="http://www.sabado.info/image/guitar.gif";

//_---------SEGUIR HASTA LA SEMANA 52--------------------------

//----------NO EDITAR A PARTIR DE AQUÍ---------------------
var cantidadDeDias=0;
var 
semana=1
diaspormes
=new Array(31,28+bisiesto,31,30,31,30,31,31,30,31,30,31
);
hoy=new Date;
anio=hoy.getYear()
primero=new Date(anio,0,1)
diasem=primero.getDay()
dia=hoy.getDate();
mes=hoy.getMonth();
for (
a=0;a<mes;a++){
cantidadDeDias=cantidadDeDias+diaspormes[a]
}
cantidadDeDias=cantidadDeDias+dia;
for (
a=0;a<cantidadDeDias;a++){
diasem=diasem+1
if (diasem>6){diasem=0;semana=semana+1}
}
//---------------------------------------------------------
</script>

</head>

<body>
<script>
document.write("<A HREF="+enlace[semana]+"><img src="+imagen[semana]+" ALT='"+alt[semana]+"'></A>");
</script>
</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:40
  #104 (permalink)  
Antiguo 12/02/2003, 12:33
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
104.- Enlaces autoexplicativos

P.- ¿Cómo poner enlaces con una explicación desplegable del mismo abajo?

R.- Así:

[Ver Ejemplo]

Código PHP:

<html>
<
head>
<
style>
body{    font:normal 10px/20px verdana;}

blockquoteborder:solid 1px black;
            
font:normal 10px/12px verdana;
            
background:#ffffcc;
            
margin:1px 1px 1px 20px;
            
padding:5px 5px 5px 5px;
            
width:500px;
        }
.
norm{    color:blue;
        
border:none;
        
font:normal 10px/10px verdana;
          
text-decoration:underline;
    }
img{    border:none;
    }
</
style>

<
script>

//Script original de KarlanKas con la colaboración de caricatos para Forosdelweb.com


explicacion=new Array;
enlace=new Array;
texto=new Array;

//-------------------------- EDITABLE ---------------------------
enlace[0]="http://www.forosdelweb.com";
texto[0]="Ir a foros del web."
explicacion[0]="Foros del Web es el foro de programación hispana más visitado por los habitantes de la luna de Gaminedes.";

enlace[1]="http://www.webareyou.com";
texto[1]="Visitar Web Are You. La página en eterna construcción."
explicacion[1]="Todos los seres abducidos tienen, desde la LSSI, la obligación de tener una página web explicando sus experiencias. Aquí está la mía.";

enlace[2]="http://www.estiloweb.com";
texto[2]="Necesitas ayuda?"
explicacion[2]="Cuando uno se enfrenta a la realización de una página web siempre le surgen dudas... con webestilo.com se resuelve más de una...";

enlace[3]="http://www.tunait.com";
texto[3]="Quieres charlar, divertirte y demás con la página de tunait?"
explicacion[3]="Nuestra querida tunait nos regala una magnífica página donde su plato fuerte es un magnífico foro lleno de buen rollito y diversión... no os lo perdais!";

enlace[4]="http://www.pepemolina.com";
texto[4]="Qué tal visitar la página de caricatos?"
explicacion[4]="Quien no recuerda el generador de código o el enviador de postales...? Caricatos no sólo responde, sino que genera nuevas inquietudes a cada momento. Visitad la página donde recoge todos sus avances!";

// SE PUEDE PONER TANTOS COMO SE QUIERA

//---------------------------------FIN DE CÓDIGO EDITABLE--------------------------------

function anadir(texto,esto){
t=texto
texto
=document.getElementById("enlace"+texto)
if(!
texto.primero){texto.primero=texto.innerHTML}
if(
isNaN(texto.ensenar)){texto.ensenar=-1}
var 
pepe=texto.ensenar
pepe
=pepe*-1
texto
.ensenar=pepe
if (texto.ensenar==1){
esto.innerHTML="-";
texto.innerHTML=texto.innerHTML+"<blockquote>"+explicacion[t]+"</blockquote>"

}
if (
texto.ensenar==-1){
;
texto.innerHTML=texto.primero
}


}

</script>
<title>FAQ 104.- Enlaces autoexplicativos </title>
</head>

<body>

<script>
for (w=0;w<enlace.length;w++){
document.writeln('<div id="enlace'+w+'"><a onfocus="blur()" href="#" onclick="anadir('+w+',this)">+</a><a class="norm" HREF="'+enlace[w]+'" target="_blank">'+texto[w]+'</a></div>');
}
</script>
</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:41
  #105 (permalink)  
Antiguo 13/02/2003, 10:16
Avatar de TurKa  
Fecha de Ingreso: enero-2003
Ubicación: Gerli, Avellaneda
Mensajes: 543
Antigüedad: 21 años, 2 meses
Puntos: 4
105.- Selects

P: ¿Como puedo hacer para que al cambiar la opción seleccionada en un combo, cambien también las opciones disponibles en otro combo indicando la URL de destino?

R: [ver ejemplo]
Código PHP:
<!-- basado en el código original propuesto por Kaopectate -->
<
html>
 <
head>
  <
script language="JavaScript">

   function 
addOpt(oCntrliPossTxtsVal){
     var 
selOpcion=new Option(sTxtsVal);
     eval(
oCntrl.options[iPos]=selOpcion);
   }

   function 
cambia(oCntrl){
    switch (
document.frm.pais.selectedIndex){
     case 
0
      
addOpt(oCntrl,  0"Ciudad de México""http://www.mexico.com");
      
addOpt(oCntrl,  1"Monterrey""http://www.monterrey.com");
      
addOpt(oCntrl,  2"Guadalajara""http://www.guadalajara.com");
      break;
     case 
1
      
addOpt(oCntrl,  0"Madrid""http://www.madrid.com");
      
addOpt(oCntrl,  1"Barcelona""http://www.barcelona.com");
      
addOpt(oCntrl,  2"San Sebastián""http://www.sansebastian.com");
      break;
     case 
2
      
addOpt(oCntrl,  0"Caracas""http://www.caracas.com");
      
addOpt(oCntrl,  1"Maracay""http://www.maracay.com");
      
addOpt(oCntrl,  2"Valencia""http://www.valencia.com");
      break;
    }
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0" width="482">
    <tr>
     <td width="25">
      Pais
     </td>
     <td width="89">
      <select name="pais" onchange="cambia(document.frm.ciudad)">
       <option value="Mex">Mexico</option>
       <option value="Esp">España</option>
       <option value="Ven">Venezuela</option>
      </select>
     </td>
     <td width="6">
      &nbsp;
     </td>
     <td width="44">
      Ciudad
     </td>
     <td width="296">
      <select name="ciudad" onChange="location.href=this.form.ciudad.options[this.form.ciudad.selectedIndex].value">
       <option value="0">Ciudad de México</option>
       <option value="1">Monterrey</option>
       <option value="2">Guadalajara</option>
      </select> <input type="button" value="Ir a..." onClick="location.href=this.form.ciudad.options[this.form.ciudad.selectedIndex].value"</td>
    </tr>
   </table>
  </form>
 </body>
</html> 
  #106 (permalink)  
Antiguo 15/02/2003, 08:56
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
106. Cómo cambiar una imagen al hacer un MouseOver


P.-¿Cómo puedo cambiar la imagen de fondo de la página o una imagen cualquiera de la misma al hacer un mouseOver sobre un enlace?
R.-Con este código:
[Ver ejemplo]


Código PHP:
<html>
<
head>
<
style>
A{text-decoration:none;
color:#330099;
font:bold 10px/15px verdana;
}
A:HOVER{text-decoration:underline;}
</
style>
    <
title>Ejemplillo</title>
    <
script>

// Quiero agradecer públicamente la gran ayuda de tunait.
// Por enseñarme, entre otras muchas cosas, la importancia de la elección de la denominación de variables. 
// Estas variables pretenden ser una aplicación práctica de tantas conversaciones sobre las mismas. X·D



    
codigoQueTeAhorrasPicar="";
    
    function 
crear(a,b,c,d){
    
this.tezto=a;
    
this.ondeVa=b;
    
this.tieneSuImagensitaYTo=new Image
    this
.tieneSuImagensitaYTo.src=c;
    if(
d){this.queFotoCambio=d}
    }
//unEnlasito=new crear([TEXTO QUE APARECE EN EL ENLACE],[DESTINO DEL ENLACE],[RUTA DE LA IMAGEN],[ID DE LA IMAGEN QUE CAMBIA- SI SE DEJA EN BLANCO SE CAMBIA EL FONDO DE LA PÁGINA]);
    
unEnlasito=new Array;
    
unEnlasito[0]=new crear("Veamos la página de Tunait","http://www.tunait.com","http://www.tunait.com/encuentros/encuentrosb.jpg","macario");
    
unEnlasito[1]=new crear("Veamos la de Caricatos","http://www.pepemolina.com","http://www.forosdelweb.com/avatar.php?userid=18599&dateline=1037047895");
    
unEnlasito[2]=new crear("Quieres ver la página de Web Are You?","http://www.karlankas.net","http://www.webareyou.com/logo.jpg");

// fonditoMono=[EL FONDO QUE SE QUIERE PARA LA PÁGINA]    

    
fonditoMono="White url('http://www.klasic.org/img/klasic.jpg') no-repeat fixed center";
    
//---------------------------------------- NO TOQUES A PARTIR DE AQUI SI NO SABES LO QUE HACES ---------------------
    
for (principio=0;principio<unEnlasito.length;principio++){
    
codigoQueTeAhorrasPicar=codigoQueTeAhorrasPicar+"<a href="+unEnlasito[principio].ondeVa+" onmouseout='noQuieroVe(unEnlasito["+principio+"])' onmouseover='quieroVe(unEnlasito["+principio+"])'>"+unEnlasito[principio].tezto+"</a><br>";
    }
    
    function 
quieroVe(etoMimamente){
    if (
etoMimamente.queFotoCambio!=null){
    
fotilloPaCambia=document.getElementById(etoMimamente.queFotoCambio);
    
fotilloPaCambia.src=etoMimamente.tieneSuImagensitaYTo.src;
    }
    else{
cuerpoSerrano.style.background="White url("+etoMimamente.tieneSuImagensitaYTo.src+") no-repeat fixed center";}
    }
    function 
noQuieroVe(etoMimamente){
    if (
etoMimamente.queFotoCambio!=null){
    
fotilloPaCambia=document.getElementById(etoMimamente.queFotoCambio);
    
fotilloPaCambia.style.visibility="hidden";
    }
    else{
cuerpoSerrano.style.background=fonditoMono;}
    }
    
//----------------------------------- HALE, YA PUEDES TOCAR ----------//
        
</script>
</head>

<body id="cuerpoSerrano" onload="document.getElementById('cuerpoSerrano').style.background=fonditoMono">

<script>document.write(codigoQueTeAhorrasPicar)</script>

<!-- ESTAS IMAGENES SON DE PRUEBA. 'TUNAIT' CAMBIA LA FOTO MACARIO. 
SI ESTAS IMAGENES TIENEN CONTENIDO DESDE EL PRINCIPIO QUITA EL ONLOAD Y EL STYLE---->

<img id=pepe style="visibility:hidden" onLoad="this.style.visibility='visible'"><br>

<img id=juan style="visibility:hidden" onLoad="this.style.visibility='visible'"><br>

<img id=macario style="visibility:hidden" onLoad="this.style.visibility='visible'"><br>

</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 26/02/2003 a las 06:44
  #107 (permalink)  
Antiguo 18/02/2003, 17:48
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
107.- Sumar (o restar) días a una fecha

P: ¿Como puedo sumar o restar días a una fecha?

R: [ver ejemplo]

Código PHP:
<html>
<
head>
 <
script language="JavaScript">

  var 
aFinMes = new Array(312831303130313130313031);

  function 
finMes(nMesnAno){
   return 
aFinMes[nMes 1] + (((nMes == 2) && (nAno 4) == 0)? 10);
  }

   function 
padNmb(nStrnLensChr){
    var 
sRes String(nStr);
    for (var 
0nLen String(nStr).lengthi++)
     
sRes sChr sRes;
    return 
sRes;
   }

   function 
makeDateFormat(nDaynMonthnYear){
    var 
sRes;
    
sRes padNmb(nDay2"0") + "/" padNmb(nMonth2"0") + "/" padNmb(nYear4"0");
    return 
sRes;
   }
   
  function 
incDate(sFec0){
   var 
nDia parseInt(sFec0.substr(02), 10);
   var 
nMes parseInt(sFec0.substr(32), 10);
   var 
nAno parseInt(sFec0.substr(64), 10);
   
nDia += 1;
   if (
nDia finMes(nMesnAno)){
    
nDia 1;
    
nMes += 1;
    if (
nMes == 13){
     
nMes 1;
     
nAno += 1;
    }
   }
   return 
makeDateFormat(nDianMesnAno);
  }

  function 
decDate(sFec0){
   var 
nDia Number(sFec0.substr(02));
   var 
nMes Number(sFec0.substr(32));
   var 
nAno Number(sFec0.substr(64));
   
nDia -= 1;
   if (
nDia == 0){
    
nMes -= 1;
    if (
nMes == 0){
     
nMes 12;
     
nAno -= 1;
    }
    
nDia finMes(nMesnAno);
   }
   return 
makeDateFormat(nDianMesnAno);
  }

  function 
addToDate(sFec0sInc){
   var 
nInc Math.abs(parseInt(sInc));
   var 
sRes sFec0;
   if (
parseInt(sInc) >= 0)
    for (var 
0nInci++) sRes incDate(sRes);
   else
    for (var 
0nInci++) sRes decDate(sRes);
   return 
sRes;
  }

  function 
recalcF1(){
   
with (document.formulario){
    
fecha1.value addToDate(fecha0.valueincrem.value);
   }
  }

 
</script>
</head>
<body>
 <form name="formulario">
  <table>
   <tr>
    <td align="right">
     Fecha (dd/mm/aaaa):
    </td>
    <td>
     <input type="text" name="fecha0" size="10">
    </td>
   </tr>
   <tr>
    <td align="right">
     Incremento:
    </td>
    <td>
     <input type="text" name="increm" size="3">
    </td>
   </tr>
   <tr>
    <td align="right">
     Resultado (dd/mm/aaaa):
    </td>
    <td>
     <input type="text" name="fecha1" disabled size="10">
    </td>
   </tr>
   <tr>
    <td colspan="2" align="center">
     <input type="button" onclick="recalcF1()" value="Calcular">
    </td>
   </tr>
  </table>
 </form>
</body>
</html> 

Última edición por Kaopectate; 19/02/2003 a las 11:29
  #108 (permalink)  
Antiguo 19/02/2003, 02:49
Avatar de epa2  
Fecha de Ingreso: abril-2002
Ubicación: Málaga
Mensajes: 1.475
Antigüedad: 21 años, 11 meses
Puntos: 9
108.- Saludar al visitante por su país de procedencia.

P: ¿Como puedo saludar al visitante según su pais de origen?.

R: Con este código.

Tomado de: Elosan

Código:
 <script>
 nul = "";
 if (navigator.userLanguage == "es") nul = "España";
 if (navigator.userLanguage == "es-mx") nul = "Mejico";
 if (navigator.userLanguage == "es-gt") nul = "Guatemala";
 if (navigator.userLanguage == "es-cr") nul = "Costa Rica";
 if (navigator.userLanguage == "es-do") nul = "Republica Dominicana";
 if (navigator.userLanguage == "es-pa") nul = "Panama";
 if (navigator.userLanguage == "es-ve") nul = "Venezuela";
 if (navigator.userLanguage == "es-co") nul = "Colombia";
 if (navigator.userLanguage == "es-pe") nul = "Perú";
 if (navigator.userLanguage == "es-ar") nul = "Argentina";
 if (navigator.userLanguage == "es-ec") nul = "Ecuador";
 if (navigator.userLanguage == "es-cl") nul = "Chile";
 if (navigator.userLanguage == "es-uy") nul = "Uruguay";
 if (navigator.userLanguage == "es-py") nul = "Paraguay";
 if (navigator.userLanguage == "es-bo") nul = "Bolivia";
 if (navigator.userLanguage == "es-sv") nul = "El Salvador";
 if (navigator.userLanguage == "es-hn") nul = "Honduras";
 if (navigator.userLanguage == "es-ni") nul = "Nicaragua";
 if (navigator.userLanguage == "es-pr") nul = "Puerto Rico";
 if (nul == "") document.write("Gracias por visitarnos.");
 else document.write("Gracias por visitarnos desde " + nul +".")
</script>
__________________

***Aprendiz de todo y maestro de nada***

Última edición por Kaopectate; 23/03/2003 a las 10:37
  #109 (permalink)  
Antiguo 19/02/2003, 11:27
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
109.- Valores iniciales de un rango de fechas

P: ¿Como puedo asignar los valores iniciales a un rango de fechas?

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
  
   
// Funciones comunes a todos los métodos de selección

   
function padNmb(nStrnLensChr){
    var 
sRes String(nStr);
    for (var 
0nLen String(nStr).lengthi++)
     
sRes sChr sRes;
    return 
sRes;
   }

   function 
makeDateFormat(nDaynMonthnYear){
    var 
sRes;
    
sRes padNmb(nDay2"0") + "/" padNmb(nMonth2"0") + "/" padNmb(nYear4"0");
    return 
sRes;
   }
   
   function 
prevMonth(nMonth){
    return ((
nMonth 10) % 12) + 1;
   }

   function 
prevMonth_Year(nMonthnYear){
    return 
nYear - (((nMonth 10) % 12) + == 1210);
   }

   function 
lastDayOfMonth(nMonthnYear){
    var 
aMonth = new Array(312831303130313130313031);
    if ((
nMonth == 2) && (nYear == 0))
     return 
29;
    else
     return 
aMonth[nMonth 1];
   }

   function 
incDate(sFec0){
    var 
nDia parseInt(sFec0.substr(02), 10);
    var 
nMes parseInt(sFec0.substr(32), 10);
    var 
nAno parseInt(sFec0.substr(64), 10);
    
nDia += 1;
    if (
nDia lastDayOfMonth(nMesnAno)){
     
nDia 1;
     
nMes += 1;
     if (
nMes == 13){
      
nMes 1;
      
nAno += 1;
     }
    }
    return 
makeDateFormat(nDianMesnAno);
   }

   function 
decDate(sFec0){
    var 
nDia parseInt(sFec0.substr(02), 10);
    var 
nMes parseInt(sFec0.substr(32), 10);
    var 
nAno parseInt(sFec0.substr(64), 10);
    
nDia -= 1;
    if (
nDia == 0){
     
nMes -= 1;
     if (
nMes == 0){
      
nMes 12;
      
nAno -= 1;
     }
     
nDia lastDayOfMonth(nMesnAno);
    }
    return 
makeDateFormat(nDianMesnAno);
   }

   function 
addToDate(sFec0nInc){
    var 
nIncAbs Math.abs(nInc);
    var 
sRes sFec0;
    if (
nInc >= 0)
     for (var 
0nIncAbsi++) sRes incDate(sRes);
    else
     for (var 
0nIncAbsi++) sRes decDate(sRes);
    return 
sRes;
   }

   
// Funciones individuales de cada método de selección

   // Esta semana completa (Lun -> Dom)
   
function setDefaults1(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
nDOW dToday.getDay();
    var 
sFirstDatesLastDate;

    if (
nDOW == 0nDOW 7;
    
sFirstDate addToDate(makeDateFormat(nDaynMonthnYear), -* (nDOW 1));
    
sLastDate addToDate(sFirstDate6);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Lo que va de esta semana (Lun -> Hoy)
   
function setDefaults2(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
nDOW dToday.getDay();
    var 
sFirstDatesLastDate;

    if (
nDOW == 0nDOW 7;
    
sLastDate makeDateFormat(nDaynMonthnYear);
    
sFirstDate addToDate(sLastDate, -* (nDOW 1));
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// La semana pasada (Lun -> Dom)
   
function setDefaults3(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
nDOW dToday.getDay();
    var 
sFirstDatesLastDate;

    if (
nDOW == 0nDOW 7;
    
sLastDate addToDate(makeDateFormat(nDaynMonthnYear), -nDOW);
    
sFirstDate addToDate(sLastDate, -6);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Los últimos siete días
   
function setDefaults4(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sLastDate makeDateFormat(nDaynMonthnYear);
    
sFirstDate addToDate(sLastDate, -6);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Este mes completo
   
function setDefaults5(oFromoTo){
    var 
dToday = new Date();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sFirstDate makeDateFormat(1nMonthnYear);
    
sLastDate makeDateFormat(lastDayOfMonth(nMonthnYear), nMonthnYear);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Lo que va de este mes
   
function setDefaults6(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sFirstDate makeDateFormat(1nMonthnYear);
    
sLastDate makeDateFormat(nDaynMonthnYear);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// El mes pasado
   
function setDefaults7(oFromoTo){
    var 
dToday = new Date();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
nYear prevMonth_Year(nMonthnYear);
    
nMonth prevMonth(nMonth);
    
sFirstDate makeDateFormat(1nMonthnYear);
    
sLastDate makeDateFormat(lastDayOfMonth(nMonthnYear), nMonthnYear);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Los últimos treinta días
   
function setDefaults8(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sLastDate makeDateFormat(nDaynMonthnYear);
    
sFirstDate addToDate(sLastDate, -29);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Este año completo
   
function setDefaults9(oFromoTo){
    var 
dToday = new Date();
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sFirstDate makeDateFormat(11nYear);
    
sLastDate makeDateFormat(3112nYear);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Lo que va de este año
   
function setDefaults10(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sFirstDate makeDateFormat(11nYear);
    
sLastDate makeDateFormat(nDaynMonthnYear);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// El año pasado
   
function setDefaults11(oFromoTo){
    var 
dToday = new Date();
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sFirstDate makeDateFormat(11nYear 1);
    
sLastDate makeDateFormat(3112nYear 1);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   
// Los últimos 365 días
   
function setDefaults12(oFromoTo){
    var 
dToday = new Date();
    var 
nDay dToday.getDate();
    var 
nMonth dToday.getMonth() + 1;
    var 
nYear dToday.getYear();
    var 
sFirstDatesLastDate;

    
sLastDate makeDateFormat(nDaynMonthnYear);
    
sFirstDate addToDate(sLastDate, -364);
    
oFrom.value sFirstDate;
    
oTo.value sLastDate;
   }

   function 
setDefaults(oFromoTonMeth){
    switch (
nMeth){
     case 
0
      
alert("");
      break;
     case 
1:
      
setDefaults1(oFromoTo);
      break;
     case 
2:
      
setDefaults2(oFromoTo);
      break;
     case 
3:
      
setDefaults3(oFromoTo);
      break;
     case 
4:
      
setDefaults4(oFromoTo);
      break;
     case 
5:
      
setDefaults5(oFromoTo)
      break;
     case 
6:
      
setDefaults6(oFromoTo)
      break;
     case 
7:
      
setDefaults7(oFromoTo)
      break;
     case 
8:
      
setDefaults8(oFromoTo)
      break;
     case 
9:
      
setDefaults9(oFromoTo)
      break;
     case 
10:
      
setDefaults10(oFromoTo)
      break;
     case 
11:
      
setDefaults11(oFromoTo)
      break;
     case 
12
      
setDefaults12(oFromoTo)
      break;
    }
   }

  
</script>
 </head>
 <body>
  <form name="formulario">
   <table border="0">
    <tr>
     <td colspan="2" style="font-family: helvetica; text-align: center; font-size: 12; font-weight: bold">
      VALORES DE INICIO DE UN RANGO DE FECHAS
     </td>
    </tr>
    <tr height="50">
     <td align="right">
      Tipo de rango:
     </td>
     <td>
      <select name="sel" onchange="setDefaults(document.formulario.fecha_desde, document.formulario.fecha_hasta, this.selectedIndex)">
       <option>...seleccione</option>
       <option>Esta semana completa</option>
       <option>Lo que va de esta semana</option>
       <option>La semana pasada</option>
       <option>Los últimos siete días</option>
       <option>Este mes completo</option>
       <option>Lo que va de este mes</option>
       <option>El mes pasado</option>
       <option>Los últimos treinta días</option>
       <option>Este año completo</option>
       <option>Lo que va de este año</option>
       <option>El año pasado</option>
       <option>Los últimos 365 días</option>
      </select>
     </td>
    </tr>
    <tr>
     <td align="right">
      Desde (dd/mm/yyyy):
     </td>
     <td>
      <input type="text" name="fecha_desde">
     </td>
    </tr>
    <tr>
     <td>
      Hasta (dd/mm/yyyy):
     </td>
     <td>
      <input type="text" name="fecha_hasta">
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 19/02/2003 a las 11:29
  #110 (permalink)  
Antiguo 20/02/2003, 13:30
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 1 mes
Puntos: 772
110.- Imágenes en miniatura

P: ¿Como puedo poner miniaturas de mis imágenes sin tener que reducirlas con un editor gráfico?

R: Con este código:
Código PHP:
<html>
<
head>
<
script>
    function 
minifoto(foto,H,V,ancho,alto) {
        
propH ancho H;
        
propV alto V;
        if (
propH>propV) {
            
anchoF propV;
            
altoF alto;
        }
        else {
            
altoF propH;
            
anchoF ancho;
        }
        
de = (ancho anchoF) / 2;
        
su = (alto altoF) /2;
        
imagen="<div style='width:"+ancho+";height:"+alto+";border:1px outset'>";
        
imagen+="<img src='"+foto+"' widht="+anchoF+" height="+altoF;
        
imagen+=" style='position:relative; left:"+de+";top:"+su+"'>";
        
imagen+="</div>";
        
document.write(imagen);
    }
</script>
</head>

<body>
<script>
    minifoto("foto.jpg",399,291,90,80);
</script>
</body>
</html> 
A la función minifoto se pasan: el nombre de la imágen, el ancho y alto real de la imágen y el ancho y alto en el que se quiere poner la imágen. La función "encaja" la imágen en un recuadro manteniendo las proporciones.

Nota: Me recuerda el amigo Bravenap, que aunque la imágen aparece en tamaño reducido, se descarga completa, es decir, con su tamaño real, por lo que no supone reducción del tiempo de descarga. Deberá tenerse esto en cuenta si se quiere utilizar este código con imágenes muy grandes o con muchas imágenes.

Última edición por JavierB; 05/06/2003 a las 02:57
  #111 (permalink)  
Antiguo 21/02/2003, 11:39
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
111.- Selector de año, mes y día

P: ¿Como puedo hacer un selector de fecha basado en tags <select> que considere permita seleccionar cualquier fecha válida hasta el día de hoy?

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">

   var 
aMeses = new Array("Enero""Febrero""Marzo""Abril""Mayo""Junio""Julio""Agosto""Septiembre""Octubre""Noviembre""Diciembre")

   function 
padNmb(nStrnLensChr){
    var 
sRes String(nStr);
    for (var 
0nLen String(nStr).lengthi++)
     
sRes sChr sRes;
    return 
sRes;
   }

   function 
makeDateFormat(nDaynMonthnYear){
    var 
sRes;
    
sRes padNmb(nDay2"0") + "/" padNmb(nMonth2"0") + "/" padNmb(nYear4"0");
    return 
sRes;
   }
   
   function 
addOpt(oCntrliPossTxtsVal){
    var 
selOpcion = new Option(sTxtsVal);
    
oCntrl.options.add(selOpcioniPos);
   }

   function 
lastDayOfMonth(nMonthnYear){
    var 
aMonth = new Array(312831303130313130313031);
    if ((
nMonth == 2) && (nYear == 0))
     return 
29;
    else
     return 
aMonth[nMonth 1];
   }

   function 
cambia(nCambiado){
    var 
nAno;
    var 
nMes;
    
with (document.frm){
     
nAno parseInt(ano.options[ano.selectedIndex].value);
     switch (
nCambiado){
      case 
0:
       
llenaMes(mesnAno);
       break;
      case 
1:
       
nMes parseInt(mes.options[mes.selectedIndex].value);
       
llenaDia(dianAnonMes)
       break;
      case 
2:
       
nMes parseInt(mes.options[mes.selectedIndex].value);
       
nDia parseInt(dia.options[dia.selectedIndex].value);
       
res.value makeDateFormat(nDianMes 1nAno);
       break;
     }
    }
   }

   function 
llenaAno(oAno){
    var 
hoy = new Date();
    var 
ini 1960;
    
addOpt(oAno0"""");
    for (var 
ini<= hoy.getYear(); i++)
     
addOpt(oAnoini 1String(i), String(i));
   }

   function 
llenaMes(oMesnAno){
    var 
hoy = new Date();
    var 
nFin 11;
    while (
oMes.length 0oMes.remove(0);
    if (
nAno == hoy.getYear()) nFin hoy.getMonth();
    
addOpt(oMes0"""");
    for (var 
0<= nFini++)
     
addOpt(oMes1aMeses[i], String(i));
   }

   function 
llenaDia(oDianAnonMes){
    var 
hoy = new Date();
    var 
nFin lastDayOfMonth(nMes 1nAno);
    while (
oDia.length 0oDia.remove(0);
    if (
nAno == hoy.getYear() && nMes == hoy.getMonth()) nFin hoy.getDate();
    
addOpt(oDia0"""");
    for (var 
1<= nFini++)
     
addOpt(oDia1String(i), String(i));
   }

  
</script>
 </head>
 <body onload=" llenaAno(document.frm.ano)">
  <form name="frm">
   <table border="0">
    <tr>
     <td align="right">
      Año: 
     </td>
     <td>
      <select name="ano" onchange="cambia(0)" style="width: 80">
      </select>
     </td>
    </tr>
    <tr>
     <td align="right">
      Mes: 
     </td>
     <td>
      <select name="mes" onchange="cambia(1)" style="width: 80">
      </select>
     </td>
    </tr>
    <tr>
     <td align="right">
      Día: 
     </td>
     <td>
      <select name="dia" onchange="cambia(2)" style="width: 80">
      </select>
     </td>
    </tr>
    <tr>
     <td align="right">
      Fecha:
     </td>
     <td>
      <input type="text" name="res" disabled>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 21/02/2003 a las 11:41
  #112 (permalink)  
Antiguo 22/02/2003, 03:24
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 21 años, 11 meses
Puntos: 1284
112. - Sonido antes de un salto

P: ¿Cómo escuchar un sonido antes de hacer un link?

R: Adaptando este script con los valores adecuados
ver ejemplo:

Código PHP:
<html>
<
head>
<
script>
function 
ReproducirYSaltar(sonretardosalto)    {
    if (
document.alldocument.all.sound.src son;
    
document.getElementById("sound2").src son;
    
setTimeout("salto('" salto "')"retardo);
}

function 
salto(x)    {
    
location.href x;
}
</script>
</head>
<body >
<bgsound id=sound style="visibility:hidden">
<embed id=sound2 hidden=true>
<a href="javascript:ReproducirYSaltar('UNDO.MID', 3000, 'http://www.sucaricatura.com' )" >
 Enlace de caricauras </a><br>
<a href="javascript:ReproducirYSaltar('UNDO.MID', 4000, 'http://www.pepemolina.com/postales' )" >
 Enlace de Postales digitales </a><br>
<a href="javascript:ReproducirYSaltar('UNDO.MID', 6000, 'http://www.pepemolina.com/visitas/visitas.php' )" >
 Firme en mi libro de visitas </a><br>
</body>
</html> 
Créditos: Se basa en un script original de chivi nº 71 de estas FAQs
... los parámetros que acepa son el fichero de sonido, el retardo que necesita para sonar y el destino del link

Saludos
  #113 (permalink)  
Antiguo 12/03/2003, 03:02
Avatar de Helbira  
Fecha de Ingreso: octubre-2001
Ubicación: Sevilla, España
Mensajes: 1.228
Antigüedad: 22 años, 5 meses
Puntos: 5
Información 115. Cerrar una ventana principal sin confirmación (II)

P: ¿Como puedo cerrar una ventana principal sin que aparezca ningún mensaje de confirmación?

R: [Ver ejemplo]

Consiste en engañar al navegador haciéndole creer que la estamos cerrando desde su opener.

TEMA: VENTANAS

Código PHP:
<html>
<
head>
<
script language="JavaScript">
 
function 
cerrar() {
var 
ventana window.self;
ventana.opener window.self;
ventana.close();
}
 
</script>
</head>
<body>
Problema:<br>
<a href="#" onClick="window.close()">
Cerrar ventana de modo tradicional (el navegador pedirá confirmación)
</a><br><br>
Solución:<br>
<a href="#" onClick="cerrar()">
Cerrar ventana sin confirmación
</a>
</body>
</html> 


P.D.: Popito ha comprobado que esto no funciona en IE5 para MAC. Ojo: Podría ocurrir también en otros navegadores.

P.D.2:LeandroEnrique comentaba que no le funciona en Mozilla asi que me he puesto a comprobarlo en varios navegadores. Concretamente en IE6, Netscape6.2,Opera7.23 y Mozilla Firefox. He de decir que en todos ellos ha funcionado el ejemplo que aparece en esta FAQ y a diferencia de IE6 en el resto de navegadores incluso el caso de un simple window.close() tampoco te pide confirmación.


Cita:
Iniciado por frodogus
Por favor, añadir en el apartado 115 Cerrar una ventana principal sin confirmación (II) no se admite en IE7

Saludos.

Última edición por tunait; 31/01/2007 a las 04:37
  #114 (permalink)  
Antiguo 12/03/2003, 23:45
 
Fecha de Ingreso: marzo-2003
Mensajes: 2
Antigüedad: 21 años
Puntos: 0
116.- Cambiar el texto de la barra de estado

P: ¿Como puedo cambiar el texto de la barra de estado?

R: Ver ejemplo

Código PHP:
<SCRIPT LANGUAGE="JavaScript">
<!--
var 
msg="TEXTO DE LA MARQUESINA"
var delay=30
var startPos=100
var timerID=null
var timerRunning=false
var pos=0
StartScrolling
()
function 
StartScrolling(){
    
StopTheClock()
    for (var 
0startPosi++) 
    
msg=" " msg
    DoTheScroll
()
}
function 
StopTheClock(){
    if(
timerRunning)
        
clearTimeout(timerID)
    
timerRunning=false
}
function 
DoTheScroll(){
    if (
pos msg.length)
        
self.status
    
msg.substring(posmsg.length);
    else
        
pos=-1;
    ++
pos
    timerRunning
=true
    timerID

   
self.setTimeout("DoTheScroll()"delay)
}
</script> 

Última edición por Kaopectate; 17/03/2003 a las 11:19
  #115 (permalink)  
Antiguo 18/03/2003, 15:56
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
117.- Redondear un número

P: ¿Como puedo redondear un valor a una cierta cantidad de decimales?

Créditos: jordan

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   function 
redondear(numdec){
    
num parseFloat(num);
    
dec parseFloat(dec);
    
dec = (!dec dec);
    return 
Math.round(num Math.pow(10dec)) / Math.pow(10dec);
   }

   function 
calcula(){
    
with (document.frm)
     
res.value redondear(val.valuedec.value);
   }
  
</script>
 <head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td align="right">
      Numero:
     </td>
     <td>
      <input type="text" name="val"><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Decimales:
     </td>
     <td>
      <input type="text" name="dec"><br>
     </td>
    </tr>
    <tr>
     <td>
      &nbsp;
     </td>
     <td align="center">
      <input type="button" name="calc" value="Redondear" onclick="calcula()">
     </td>
    </tr>
    <tr>
     <td align="right">
      Resultado:
     </td>
     <td>
      <input type="text" name="res"><br>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 
  #116 (permalink)  
Antiguo 27/03/2003, 10:15
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
118.- (me gustan los bizcochos) Buscador interno

P.-¿Cómo pongo un buscador interno en mi site?
R.- Siguiendo estos sencillos pasos:

Cómo instalar un buscador, el APB Search 1.12 (que es
gratuito)


Hay otra versión que es de pago con más características, pero
creo que esta basta y sobra para la mayoría. A mi modo de ver es
bastante bueno, aunque supongo que cada uno tendrá el de su
preferencia.

Pasos a seguir:

1.- Descargar el archivo apbsearch.zip
de apbsystems.com


2.- Dentro hay 5 archivos:
  • archive.cgi
  • readme11.txt
  • search.cgi
  • searchBottom.html
  • searchTop.html
Copiamos todos (salvo el txt) en el directorio CGI-BIN del servidor
donde tengamos alojada la página. Es importante que dicho
upload
se haga en modo texto (ver configuración de vuestro
programa FTP).

3.- Una vez subidos dais permisos (CHMOD) a los archivos
con extensión CGI (search y archive) de forma que quede como
en la imagen:




4.- Debes llamar, si no lo sabes, a tu proveedor de hosting
para preguntar la ruta absoluta dentro del servidor de tu página.

5.- Una vez hecho esto con el navegador ve a esta página:

http://www.tudominio.com/cgi-bin/archive.cgi

Tal vez el acceso a tu directorio de CGI sea otro, pregunta al
proveedor de tu hospedaje.

6.- si todo va bien pasa al punto 7, si no, si te sale un error
500 comprueba los permisos del archivo archive.cgi, comprueba
que lo has subido en modo texto. Si te dice que no lo encuentra
comprueba que la ruta es la correcta (ya os he dicho que la ruta
puede que no sea la puesta, hay hospedajes cuya ruta es
cgi.tudominio.com...).

7.- Aparecerá una página de diseño bastante discreto:

que te preguntará el dominio de la página, la ruta absoluta de la
misma dentro del servidor y la extensión de los archivos que
quieres indexar. Rellénalo como debas y dale a siguiente.

8.- Ahora debes seleccionar los directorios que quieres que
indexe. Fíjate que no está marcado un directorio que no
contenga archivos web (imágenes, scripts...).

9.- Por último des-selecciona los archivos que no quieras
que indexe (prueba3.html y cosas por el estilo que siempre se
quedan pululando).

10.- Si todo ha ido bien aparecerá una ventana
confirmando que ya está.

11.- Ve al directorio CGI-BIN de tu servidor y cambia los
permisos de el archivo archive.cgi a 600 para evitar que alguien
malintencionado te modifique la lista de archivos.

12.- Añade el siguiente código a la página de búsqueda:

Código:
<form action="/cgi-bin/search.cgi" method="get">
<input type="text" name="search" size=27>
<input type="submit">
</form>

13.- Editad los archivos searchTop.html y
searchBottom.html para dar una imagen a la página de
resultados acorde con vuestra página web.
Y ya está!!

Espero que os haya ayudado. Si no es así espero vuestras dudas.

Un saludo!

Me alegraría que si usas esta faq comentaras que es mía.
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:43
  #117 (permalink)  
Antiguo 30/03/2003, 01:59
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 21 años, 11 meses
Puntos: 1284
119.- Reemplazar

P . - ¿Cómo reemplazar o eliminar subcadenas de una cadena?

R . - Combinando el método split para convertir una cadena en un array y join que hace lo contrario...
Poniendo como párámetro del split, lo que se quiere quitar, y en join la nueva subcadena (cadena vacía para eliminar)

Ejemplo:
var invertirBarra = "Hola/amigos/del/foro".split("/").join("\");

deja la variable invertirBarra = "Hola\amigos\del\foro";

Nota: Este sistema mejora el que propuse en otra discusión para insertar emoticones en un textarea

Saludos

Última edición por Kaopectate; 31/03/2003 a las 10:15
  #118 (permalink)  
Antiguo 15/04/2003, 11:06
Avatar de ferny
Il capo della mafia
 
Fecha de Ingreso: febrero-2002
Ubicación: Al final del cable
Mensajes: 10.080
Antigüedad: 22 años, 1 mes
Puntos: 55
120.- Link al MSN

P.- ¿Cómo puedo hacer un link en la web para agregar un contacto messenger?

R.- Puedes utilizar lo siguiente:
Código:
<OBJECT height='1' id='MsgrObj' width='1'></OBJECT>
<script>
function DoInstantMessage(person,screen)
{
	//Check if person has messenger installed
	try{MsgrObj.classid="clsid:B69003B3-C55E-4B48-836C-BC5946FC3B28";}
	catch(e){if(!(e.number && 2148139390) == 2148139390)return;}
	
	//Check if you are logged in
	if(MsgrObj.MyStatus == 1)
	{
		alert("You are not logged into Messenger.\nYou must login to Messenger before continuing.");
		return;
	}
	
	//Check if person is already in contact list
	try{var contact = MsgrObj.GetContact(person,"");}
	catch(e)
	{
		if((e.number && 2164261642) == 2164261642) //MSGR_E_USER_NOT_FOUND
		{
			if(confirm("Add "+screen+" to your contact list?")==true)MsgrObj.AddContact(0,person);
		}
	}
	
	//Ask to send an instant message
	if(confirm("Send "+screen+" an instant message?")==true)MsgrObj.InstantMessage(person);
}
</script>
Luego llamas a la función así:
Código:
<a href=javascript:DoInstantMessage("[email protected]","nombre")>Messenger</a>
O bien usa una imagen como enlace.

IMPORTANTE: sólo funciona en Internet Explorer.

Créditos: mods de phpBB - MSN Messenger Mod
__________________
www.mundodivx.com || www.mundodivx.org

Pon tu mano en un horno caliente durante un minuto y te parecerá una hora.
Siéntate junto a una chica preciosa durante una hora y te parecerá un minuto.
Eso es la relatividad.
  #119 (permalink)  
Antiguo 28/04/2003, 04:10
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
121. Barra personalizada de scroll

P.- ¿Cómo hacer una barraa de scroll personalizada con los iconos formas y colores que quiera?
R.- Por medio de este script:
(Compatible con Opera 7, NS 6.2 y IE 5.0)

Código PHP:

<html>
<
head>
    <
title>Barra de desplazamiento</title>
    <
script>
//Script original de KarlanKas para Forosdelweb.com


//Muchas gracias a todos los que colaboraron en la elaboración de este script, en especial a JavierB, artífice de la compatibilidad del mismo con NS. 

    
ancho=700;
    
altoVentana=300;
    
altoContenido=700;
    
altoBoton=20;
    
anchoBoton=15;
    
incremento=5;
    
//    ---------------------------NO EDITAR--------------------------------
    
recorrido=altoVentana-(2*altoBoton)
    
altoBarra=recorrido*(altoVentana/altoContenido);
    
recorridoBarra=recorrido-altoBarra;
    
incrementoBarra=incremento*(recorridoBarra/(altoContenido-altoVentana));
    
recorridoAcumuladoBarra=0;
    
recorridoAcumuladoContenido=0;
    
anchoContenido=ancho-anchoBoton;
    
no=false;
    var 
yy=0;
    
pulsado=false;
    var 
mouseY;
    
    if (
altoVentana>=altoContenido){no=true}
    
altoBarra+=incrementoBarra+1
    
    
    
    
    estilo
='<style>';
    
estilo+='#ventana{'
    
estilo+='            height:'+altoVentana+'px;';
    
estilo+='            width:'+ancho+'px;';
    
estilo+='               z-index:1;';
    
estilo+='            border:solid 1px black;';
    
estilo+='            overflow:hidden;';
    
estilo+='            position:relative;';
    
    
estilo+='}'
    
    
    
    
estilo+='#botonArriba{        position:absolute;';
    
estilo+='                    padding:0px 0px 0px 0px;';
    
estilo+='                    font:normal 8px/8px courier;';
    
estilo+='                    top:0px;';
    
estilo+='                    width:'+anchoBoton+'px;';
    
estilo+='                    height:'+altoBoton+'px;';

    
estilo+='                       z-index:99;';
    
estilo+='                       cursor:hand;';
    
estilo+='                       left:'+(ancho-anchoBoton)+'px;';
    
estilo+='    }'
    
estilo+='#botonAbajo{        position:absolute;';
    
estilo+='                    padding:0px 0px 0px 0px;';
    
estilo+='                    font:normal 9px/9px courier;';
    
estilo+='                    width:'+anchoBoton+'px;';
    
estilo+='                    height:'+altoBoton+'px;';
    
estilo+='                    top:'+(altoVentana-altoBoton)+'px;';
    
estilo+='                       left:'+(ancho-anchoBoton)+'px;';
    
estilo+='                       z-index:99;';
    
estilo+='                       cursor:hand;';
    
estilo+='}';
    
estilo+='</style>';    
    
    
estiloContenido='style="';
     
estiloContenido+='            width:'+(anchoContenido)+'px;';
    
estiloContenido+='            padding:10px 10px 10px 10px;';
    
estiloContenido+='            font:normal 10px/15px verdana;';
    
estiloContenido+='            position:absolute;';
    
estiloContenido+='            top:0px;'

    
estiloContenido+='            left:0px;'
    
estiloContenido+='            background:#ffffcc;';
    
estiloContenido+='            border-right:solid black 1px;';
     
estiloContenido+='            height:'+altoContenido+'px;'
;
    
estiloContenido+='            overflow:hidden;';
    
estiloContenido+='            text-align:justify;"';    
    
    
estiloBarra='style="position:absolute;';
    
estiloBarra+='                    width:'+anchoBoton+'px;';
    
estiloBarra+='                    position:absolute;';
    
estiloBarra+='                    top:'+altoBoton+'px;';
    
estiloBarra+='                       z-index:99;';
    
estiloBarra+='                       cursor:hand;';
    
estiloBarra+='                       left:'+(ancho-anchoBoton)+'px;';
    if (
no){estiloBarra+='            visibility:hidden;';}
    
estiloBarra+='                    height:'+altoBarra+'px;"';



    
document.write(estilo);

</script>


    

    <script for="ventana" event="onmousewheel">
    if(document.all){mover(event.wheelDelta/30)}
    </script>
    <script >
    function ratonAbajo(){
    
    if (document.all){yy=event.clientY;}
    else{yy = coorY; }
    pulsado=true;}
    </script>
    <script>

function mover(hacia){

    nB=parseInt(document.getElementById("barra").style.top);
    nC=parseInt(document.getElementById("contenido").style.top);


if (((nC+(hacia*incremento))<incremento) && (nC+(hacia*incremento)>(altoVentana-altoContenido))){
recorridoAcumuladoBarra-=(hacia*incrementoBarra);
recorridoAcumuladoContenido+=(hacia*incremento);
    
if(recorridoAcumuladoContenido>0){recorridoAcumuladoContenido=0}
if(recorridoAcumuladoBarra<altoBoton){recorridoAcumuladoBarra=altoBoton}
if(recorridoAcumuladoBarra> (recorridoBarra+altoBoton)){recorridoAcumuladoBarr
a=recorridoBarra+altoBoton}
    
    document.getElementById("contenido").style.top=recorridoAcumuladoContenido;
    document.getElementById("barra").style.top=recorridoAcumuladoBarra;
    
    }}

    
function ratonMoviendose(){
if(pulsado){
            if (document.all){y=event.clientY;}
else{
    y = coorY; }
yy=yy-y;
yyy=yy/incrementoBarra;
mover(yyy);
yy=y;
}}
    function seVa(){
    pulsado=false;
    
    }
    </script>
</head>

<body>
<div     id="ventana">        
        <script>
        document.write('<div id="contenido" '+estiloContenido+'>');
        </script>
                
1 Texto<br>
2 Texto<br>
3 Texto<br>
4 Texto<br>
5 Texto<br>
6 Texto<br>
7 Texto<br>
8 Texto<br>
9 Texto<br>
10 Texto<br>
-----------------------------------------<br>
11 Texto<br>
12 Texto<br>
13 Texto<br>
14 Texto<br>
15 Texto<br>
16 Texto<br>
17 Texto<br>
18 Texto<br>
19 Texto<br>
20 Texto<br>
-----------------------------------------------------
------------------------------------------------------
-----------------------------------------------------
---------------------------</br>
21 Texto<br>
22 Texto<br>
23 Texto<br>
24 Texto<br>
25 Texto<br>
26 Texto<br>

        </div>
        <input type="button"
                value="?"
                id="botonArriba"
                onMouseOver="pepe22=window.setInterval('mover(1)',20)"
                onMouseOut="window.clearInterval(pepe22)">
        
        <input type="button"
                value="?"
                id="botonAbajo"
                onMouseOver="if(no==false){pepe22=window.setInterval('mover(-1)',20)}"
                onMouseOut="if(!no){window.clearInterval(pepe22)}"
                >
        
        <script>
        document.write('<input type="button"');
        document.write(' id="barra"  onMouseDown="ratonAbajo()"');
        document.write('  onMouseMove="ratonMoviendose()"');
        document.write('   onMouseUp="seVa()" onMouseOut="seVa()" ');
        document.write(estiloBarra);
        document.write(' >');
        
//----------------------RATON EN NS-------------------------------
document.onmousemove = mouseMove;
var ns6 = (document.getElementById && !document.all) ? true: false;
var coorY;
if (ns6) document.getElementById('barra').addEventListener("mousemove", mouseMove, true)
function mouseMove(e)
{
if (ns6)    {coorY = e.pageY;}
return true;
}
</script>
</div>
</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:44
  #120 (permalink)  
Antiguo 28/04/2003, 05:53
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
122.- Cómo poner un reloj analógico en mi web

P.- Cómo poner un reloj analógico en mi web.
R.- En realidad este post es un ejemplo de como manejar grados con JS. Para ello he hecho este relojillo en el que es la hora, son los segundos y los minutos.

Caricatos (hola campeón!!) tiene un ejemplo mucho más completo aunque tal vez un poco más complicado (por lo completo que es).

Lo he modificado un poco... ahora tiene manecillas!

11/11/2004
Lo he vuelto a modificar. Ahora es compatible con Mozilla, Firefox, Opera 7...

[ver ejemplo]

Ahí va!


Código PHP:
<html>
<
head>
<
title>Reloj analogico</title>
<
script>
//Script original de KarlanKas para Forosdelweb.com


var codigo="";
var 
incremento=-1
var radio=110
var radio2=100
radianes
=(2*3.141592/360)

function 
crear(nombr,radi,hor,destin){
this.nombre=nombr;
this.radio=radi;
this.hora=hor;
this.destino=destin;
}

manecillas=new Array();
manecillas[0]=new crear("segundero",1,"segundo","http://www.forosdelweb.com/images/smilies/dedosabajo.gif");
manecillas[1]=new crear("minutero",0.8,"minuto","http://www.forosdelweb.com/images/smilies/dedosarriba.gif");
manecillas[2]=new crear("horero",0.5,"hora","http://www.forosdelweb.com/images/smilies/wink.gif");

// -------------- DIBUJAR MANECILLAS ---------------------------
for(numeroIconos=0;numeroIconos<5;numeroIconos++){
for(
cadaManecilla=0;cadaManecilla<3;cadaManecilla++){
codigo+='<img id="'+manecillas[cadaManecilla].nombre+numeroIconos+'" style="z-index:2;position:absolute;top:-300px;" src="'+manecillas[cadaManecilla].destino+'">\n'}
}
//----------- PONER EL CENTRO DE LA ESFERA---------------------------------

codigo+='<img style="z-index:4;position:absolute;top:110px;left:110px;" src="http://www.forosdelweb.com/images/smilies/smile.gif">'

//------------- DIBUJAR ESFERA --------------------------
for(numero=0;numero<=359;numero+=30){
x=Math.floor((radio2)*Math.cos(radianes*numero));
y=Math.floor((radio2)*Math.sin(radianes*numero));
document.write('<img src="http://www.forosdelweb.com/images/smilies/risa.gif" style="position:absolute;left:'+(radio+x)+'px;top:'+(radio+y)
+
'px">');
}

//------------------ MAQUINARIA DEL RELOJ --------------

function reloj(){

//-------------SABER LA HORA----------------
ahora=new Date();

document.title=ahora.toLocaleString()

segundo=ahora.getSeconds()*6
minuto
=ahora.getMinutes()*6
hora
=(ahora.getHours()*30)

hora+=(minuto/12)

//---------PONER 0 GRAD0S EN 90 GRADOS---------------
hora-=90;
minuto-=90;
segundo-=90

//-------MOVER LAS MANECILLAS---------------

for (a=0;a<99;a=a+20){
incremento++
for (
m=0;m<3;m++){
manecilla=document.getElementById(manecillas[m].nombre+incremento);
eval(
"cosa="+manecillas[m].hora);
x=a*manecillas[m].radio*Math.cos(radianes*cosa);
y=a*manecillas[m].radio*Math.sin(radianes*cosa);
manecilla.style.left=x+radio+'px';
manecilla.style.top=y+radio+'px';

}
}
incremento=-1;
}

</script>
</head>

<body onload='reloj();window.setInterval("reloj()",50)'>

<script>document.write(codigo)</script>

</body>
</html> 
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 04/01/2005 a las 11:46
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado

SíEste tema le ha gustado a 103 personas (incluyéndote)




La zona horaria es GMT -6. Ahora son las 14:54.