Noticias Weblogs Foros Wiki Código

RecorteX

» JavaScript
326 usuarios y 203 recortes de código
Usuario

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

RSS
Recortes: 20

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

Validaciones en Javascript

Funciones en javascript que permiten validar si un campo es requerido, o si necesitamos que acepte nada mas letras, numerico o alfanumerico.
 
 function requerido(campo, id){
	if ((campo.value.length==0 || campo.value.length ==undefined) &&   campo.style.visibility!='hidden') {
		alert("El campo " + id + " es requerido");
		if(campo.type!='hidden' && !campo.disabled){
			campo.focus();
		}
		
		return false;
	} else {
		return true;
	}
}
 
function letras (campo, id) {
	var charpos = campo.value.search("[^A-Za-z]"); 
	if(campo.value.length > 0 &&  charpos >= 0) { 
		strError = "El campo " + id +" solo permite letras "; 
		alert(strError + "\n [Posicion del caracter erróneo: " + eval(charpos+1)+"]"); 
		campo.focus();
		return false; 
	} else {//if 
		return true;
	}
}
 
 
function numerico(campo, id) {
 
	var charpos = campo.value.search("[^0-9]"); 
    if (campo.value.length > 0 &&  charpos >= 0)  { 
    	strError = "El campo "+id+" solo acepta digitos "; 
	    alert(strError + "\n [El caracter erróneo esta en la posicion: " + eval(charpos+1)+"]"); 
		campo.focus();
	    return false; 
	} else {
		return true;
	}
}
 
function alfanumerico(campo, id){ 
	var charpos = campo.value.search("[^A-Za-z0-9., ]"); 
	if(campo.value.length > 0 &&  charpos >= 0) { 
		strError = "El campo "+id+" solo aceptar letras de A a la Z y digitos"; 
		alert(strError + "\n [Posición del caracter erróneo: " + eval(charpos+1)+"]"); 
		campo.focus();
		return false; 
	} else {//if 
		return true;
	}
}
 
Uso: 1. Recomiendo guardar las validaciones en un archivo aparte , por ejemplo validaciones.js
2. incluir el archivo de validaciones, de la siguiente manera
<script language="Javascript" src="../ruta/validaciones.js"></script>
3. Vamos a validar un campo que acepte puros números,
el nombre del campo o textbox será txtCodigo
4. Insertamos un boton y llamamos a la función envia mediante onclick = "envia();"
 
 
function envia() {
 
	var manda = true;//variable que toma el valor de true si cumple la validacion el campo
		if (numerico(window.document.form.txtCodigo, "Codigo"))  {
			manda = true;
		}  else {
			manda = false;
			return false;
		}
 
if (manda) {
		window.document.form.accion.value ="Inserta"; //Si los campos cumplen las validaciones 
		window.document.form.submit();	              //procedo a insertar el registro en bd
 
}
 

Redireccionar una pagina con javascript

Este fragmento de texto es una redireccion automatica que cuando el browser pasa sobre estas lineas de codigo, automaticamente redirecciona. No toma en cuenta la redireccion como un elemento de la historia del browser.

Pagina1 -> Pagina2(redirecciona a) -> Pagina3

El historico se almacena asi:

Pagina1 -> Pagina3
 
<script language="javascript" type="text/javascript">
	location.href="";
</script>
 
Es sencillo pero muy util

Mueve el scroll de una capa al pasar el ratón

Ideal para hacer un carrusel del fotos en una capa de ancho limitado, y que estas se desplacen al pasar el ratón sobre la capa.

El alto de la capa se ajustará al máximo alto de las imágenes que contenga. Estas imágenes se situarán en línea (una detrás de otra) separadas por 5 pixels.

Al pasar el ratón por la derecha o por la izquierda de la capa, se desplazará el contenido de esta para acceder a las imágenes que no aparecen en ese momento.

Código CSS necesario:
 
.st {
	position: relative; /* obligatorio */
	width : 160px;  /* ajustable */
	overflow : hidden; /* obligatorio */
}
 
Código Javascript necesario:
 
<script type="text/javascript">
window.onload = f_init;
 
var oDiv  = null;
var hInt  = null;
var nDir  = 0;
 
function f_init() {
	var nCoordX = 0;
	var nMaxH   = 0;
	var nlDivs  = document.getElementsByTagName("div");
	for(i=0; i<nlDivs.length; i++) {
		var oDiv = nlDivs[i];
		if(oDiv.className=="st") {
			oDiv.onmouseover = f_mover;
			oDiv.onmousemove = f_mmove;
			oDiv.onmouseout  = f_mout;
			oDiv.move        = f_move;
			for(ii=0; ii<oDiv.childNodes.length; ii++) {
				var oImg = nlDivs[i].childNodes[ii];
				if(oImg.tagName=="IMG") {
					oImg.style.position = "absolute";
					oImg.style.left     = nCoordX+"px";
					nCoordX += oImg.width + 5;
					nMaxH    = Math.max(nMaxH, oImg.height);
				}
			}
			oDiv.scrollLeft   = 0;
			oDiv.maxScrollW   = oDiv.scrollWidth - oDiv.offsetWidth;
			oDiv.centerX      = (oDiv.offsetWidth / 2);
			oDiv.style.height = nMaxH+"px";
		}
	}
}
function f_mover() {
	if(hInt != null) window.clearInterval(hInt);
	oDiv  = this;
	hInt  = window.setInterval(f_move, 10);
}
function f_mmove(event) {
	if(event == null) event = window.event;
	var x  = event.clientX - this.offsetLeft;
	if(x < this.centerX && this.scrollLeft>0              ) nDir = -1;
	if(x > this.centerX && this.scrollLeft<this.maxScrollW) nDir = +1;
}
function f_mout() {
	window.clearInterval(hInt);
	hInt = null;
	oDiv = null;
}
function f_move() {
	oDiv.scrollLeft += nDir;
}
 
Y código HTML de ejemplo:

<div class="st">
	<img src="imagen1.jpg" title="thumb #1" />
	<img src="imagen2.jpg" title="thumb #2" />
	<img src="imagen3.jpg" title="thumb #3" />
	<img src="imagen4.jpg" title="thumb #4" />
</div>

Cambia una imagen por otra haciendo un fundido al fondo

Cambia una imagen por otra haciendo un fundido al fondo. Funciona con múltiples imágenes, al llegar a la última regresa a la primera.

<img class="ic" src="imagenes/imagen1.jpg" srcalt="imagen2.jpg;imagen3.jpg" alt="Pulsa sobre la imágen para cambiarla por otra" />
 
window.onload = f_init;
 
var isExplorer = (document.all ? true : false);
var hFade      = null;
var imgFade    = null;
var imgAlfa    = 10;
 
function f_init() {
	var nlImgs = document.getElementsByTagName("img");
	for(i=0; i<nlImgs.length; i++) {
		if(nlImgs[i].className=="ic") {
			var nSlash = 1 + nlImgs[i].src.lastIndexOf("/");
			var sURL   = nlImgs[i].src.substr(0, nSlash);
			nlImgs[i].onclick  = f_changeImg;
			nlImgs[i].step     = 0;
			nlImgs[i].cimg     = 0;
			nlImgs[i].srcalt   = nlImgs[i].getAttribute("srcalt").split(";");
			for(ii=0; ii<nlImgs[i].srcalt.length; ii++)
				nlImgs[i].srcalt[ii] = sURL + nlImgs[i].srcalt[ii];
			nlImgs[i].srcalt[ii] = nlImgs[i].src;
			if(isExplorer)
				nlImgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.Alpha";
		}
	}
}
 
function f_changeImg() {
	window.clearInterval(hFade);
	if(this.className=="ic") imgFade = this;
	switch(imgFade.step) {
		case 0:
			imgFade.step = 1;
			f_startFadeOff();
			break;
		case 1:
			imgFade.step = 2;
			f_changeSrc();
			break;
		case 2:
			imgFade.step = 3;
			f_startFadeOn();
			break;
		case 3:
			imgFade.step = 0;
			imgFade.onclick = f_changeImg;
			break;
	}
}
 
function f_changeSrc() {
	imgFade.cimg++;
	if(imgFade.cimg == imgFade.srcalt.length) imgFade.cimg = 0;
	imgFade.src = imgFade.srcalt[imgFade.cimg];
	f_changeImg();
}
 
function f_startFadeOff() {
	imgFade.onclick = null;
	hFade   = window.setInterval(f_fadeOff, 100);
}
 
function f_fadeOff() {
	imgAlfa -= 1;
	imgFade.style.MozOpacity = (imgAlfa/10);
	if(isExplorer)
		imgFade.filters.item("DXImageTransform.Microsoft.Alpha").opacity = imgAlfa*10;
	if(imgAlfa==0) {
		f_changeImg();
	}
}
 
function f_startFadeOn() {
	imgFade.onclick = null;
	hFade   = window.setInterval(f_fadeOn,  100);
}
 
function f_fadeOn() {
	imgAlfa += 1;
	imgFade.style.MozOpacity = (imgAlfa/10);
	if(isExplorer)
		imgFade.filters.item("DXImageTransform.Microsoft.Alpha").opacity = imgAlfa*10;
	if(imgAlfa==10) {
		f_changeImg();
	}
}
 

Peticiones POST por XMLHttpRequest

Primero debemos obtener la referencia al objeto XMLHttpRequest
 
  function getHTTPObject() 
	{ var xmlhttp; 
		/*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ 
		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
		{ try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } }
		return xmlhttp; 
	} 
	var http = getHTTPObject(); // We create the HTTP Object
 
Y para poder realizar la petición mediante POST es importante la siguiente linea de enconding:
 
http.open("POST", url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
http.onreadystatechange = handleHttpResponse;
 
Siendo "handleHttpResponse" la función que queramos que trate la respuesta.
 
function handleHttpResponse() 
{
	if (http.readyState == 4) 
	{
		results = http.responseText;
               //tratar la respuesta contenida en results.
	}
}
 

funcion abrecierra() un DIV

Función abrecierra(). Se le pasa el id de un DIV y lo muestra o lo oculta alternativamente.
 
// definiciones basicas
OCULTO="none";
VISIBLE="block";
 
function abrecierra(nodo) {
  estado = document.getElementById(nodo).style.display;
  if (estado==OCULTO) {
    document.getElementById(nodo).style.display=VISIBLE;
  }
  else {
    document.getElementById(nodo).style.display=OCULTO;
  }
}
 

trim en javascript

Función sencilla que elimina los espacios (y los saltos de líneas) del principio y el final de una cadena.
 
function trim(s) {
  while (s.length>0 && (s[0]==' '||s[0]=='\n')) s=s.substring(1, s.length);
  while (s.length>0 && (s[s.length-1]==' '||s[s.length-1]=='\n')) s=s.substring(0, s.length-1);
  return s; 
}
 

Obtener un contenido text/xml con una petición HTTP

No hay mucho que decir, a veces sencillamente solo quieres poder leer ficheros XML, y luego meterlo con un .innerHTML a lo bestia, no necesitas todo un framework ajax para eso.

function getContent(sURL) {
	var xmlhttp;
	if(window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.open("GET", sURL, false);
		xmlhttp.send(null);
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		if(xmlhttp) {
			xmlhttp.open("GET", sURL, false);
			xmlhttp.send();
		}
	}
	return xmlhttp.responseXML;
}
...

Obtener un contenido text/plain con una petición HTTP

No hay mucho que decir, a veces sencillamente solo quieres poder leer ficheros de texto plano, y luego procesarlos por tu cuenta, no necesitas todo un framework ajax para eso.

function getContent(sURL) {
	var xmlhttp;
	if(window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.open("GET", sURL, false);
		xmlhttp.send(null);
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		if(xmlhttp) {
			xmlhttp.open("GET", sURL, false);
			xmlhttp.send();
		}
	}
	return xmlhttp.responseText;
}
...

Mostrar u ocultar un DIV

Lo siguiente muestra un link "Ver más" que abre un div oculto:
 
<script>
// definiciones basicas
OCULTO="none";
VISIBLE="block";
	
function mostrar(blo) {
  document.getElementById(blo).style.display=VISIBLE;
  document.getElementById('ver_off').style.display=VISIBLE;
  document.getElementById('ver_on').style.display=OCULTO;
}
 
function ocultar(blo) {
  document.getElementById(blo).style.display=OCULTO;
  document.getElementById('ver_off').style.display=OCULTO;
  document.getElementById('ver_on').style.display=VISIBLE;
}
</script>
 
Y el código HTML que lo utiliza:
 
<div id="ver_on"><a href="#" onclick="mostrar('bloque')">Ver más</a></div>
<div id="ver_off" style="display: none"><a href="#" onclick="ocultar('bloque')">Ver menos</a></div>
<div id="bloque" style="display: none">Texto a mostrar u ocultar</div>
 
info@recortex.com - Proyecto: Juanjo Navarro, 2006 - Diseño: Albin