Noticias Weblogs Foros Wiki Código

RecorteX

» html
303 usuarios y 202 recortes de código
Usuario

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

RSS
Recortes: 23

Etiquetas relacionadas:
css
javascript
rss
xhtml
php
xml
convertir
radio
imagen
div
validar
atom
países
form
correo
imprimir
electronico
barra
forma
texto
input
entidades
button
progreso
formularios
dieresis
tildes
favicon
checkbox
provincias
forumularios
diseño
vacio
acentos
letras
feeds

Generar funciones de accesibilidad de manera rapida en un formulario

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

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

Barra de progreso con CSS

Para poder hacer una barra de progreso, solo es cuestion de que pongan los vvalores dinamicos con ajax o php o asp… ;)



<style>
    .graph { 
        position: relative; /* IE is dumb */
        width: 200px; 
        border: 1px solid #000000; 
        padding: 2px; 
    }
    .graph .bar { 
        display: block;
        position: relative;
        background: #B1D632; 
        text-align: center; 
        color: #333; 
        height: 2em; 
        line-height: 2em;            
    }
    .graph .bar span { position: absolute; left: 1em; }
</style>
<div class="graph">
    <strong class="bar" style="width: 30%;">30%</strong>
</div>

Convertir letras con acentos, tildes, ... a entidades HTML

Si se quiere convertir, por ejemplo á por &aacute; y todas las demás, con esta simple función ya vale. Su funcionamiento:

1. Convierte TODOS los caracteres especiales a entidades.

2. Como los caracteres <, & y > no nos interesa que queden codificados, se vuelven a descodificar (sólo estos).

 
  function caracteres_html($texto){
      $texto = htmlentities($texto, ENT_NOQUOTES, 'UTF-8'); // Convertir caracteres especiales a entidades
      $texto = htmlspecialchars_decode($texto, ENT_NOQUOTES); // Dejar <, & y > como estaban
      return $texto;
  }
 

Si no se dispone de PHP 5 o posterior, se necesita también agregar el siguente código:

 
  if ( !function_exists('htmlspecialchars_decode') )
  {
      function htmlspecialchars_decode($text)
      {
          return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
      }
  }
 

A disfrutarlo!

Eliminar elementos al imprimir una página web

Se puede utilizar CSS para indicar que determinados elementos no se deben mostrar al emplear una página web (por ejemplo menúes de enlaces que no tienen sentido al imprimir).

Para ello añadimos un css especial para impresión dentro del HEAD:

 
<link rel="stylesheet" href="impresora.css" media="print">
 

Luego sólo tenemos que eliminar determinados elementos dentro de impresora.css:

 
#menu {
  display: none;
}
 

Imagen en vez de boton de SUBMIT

PAra todos aquellos que no quieran un simple boton en su forma al crear HTML, pueden incluir esto
 
<input type="image" src="__Direccion de la imagen__" value="About submit buttons" alt="__Texto alterno__" name="submit" style="border:0px"/>
 

Validar una Forma con Javascript

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

Limpiar HTML de una cadena

Limpia de HTML una cadena via Expresiones Regulares
 
// Limpiar HTML de una cadena
// $opcion define si la cadena de salida usara previamente un htmlentities();
function limpiarHTML($cadena,$opcion) {
   $expresion = "<[^>]+>?([^>|^<]*)<?\/[^>]*>";
 
    while (ereg($expresion,$cadena) == true) {
        $cadena = ereg_replace($expresion,'\\1',$cadena);
    }
 
    if ($opcion) {
        return htmlentities($cadena);
    } else {
        return $cadena;
    }
}
 

Firefox + RSS

Para que Firefox reconozca automaticamente que el site tiene live bookmarks (o feeds o RSS o...)
solo hay que añadir la línea de código (convenientemente rectificada para quen apunte a nuestro fichero XML

<link rel="alternate" type="application/rss+xml" title="Título RSS" href="http://host/ruta/a/fichero.rss" />

Cambiar estilos dinámicamente con cookie

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

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


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

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

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

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

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


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

Div con efecto de desvanecimiento

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

Ejemplo de uso:

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

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

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