Juglar / v.CIII

Está viendo los artículos de la categoría Javascript

Mostrar y ocultar un bloque

En la mayoría de ocasiones, tener un div oculto que se abre pulsando un enlace o un botón obedece más a un interés estético que práctico, pero también había que plantearse cómo se hace, aunque no tenga ni idea de javascript.

Observen el ejemplo en Planeta Código, que creo que es suficientemente simple e intuitivo.

El javascript:
<script type="text/javascript">
// 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>

El HTML que proponen:
<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>

Y para finalizar, mi intento de adaptarlo a un menú para el blog (ver demo), que también funciona y valida:
<div id="botonmenu">
<a id="ver_on" href="#" onclick="mostrar('bloque')">Abrir menú</a>
<a id="ver_off" style="display: none" href="#" onclick="ocultar('bloque')">Cerrar menú</a>
<ul id="bloque" style="display: none">
<li><a href="http://juglar103.blogsome.com/archivos/" title="Listado de todos los posts">Archivos</a></li>
<li><a href="http://www.bloglines.com/public/Juglar" title="Los blogs que sigo con Bloglines">BlogRoll</a></li>
<li><a href="http://del.icio.us/juglar103/" title="Mis enlaces favoritos en del.icio.us">Enlaces</a></li>
<li><a href="mailto:{the_author_email}" title="Correo electrónico">Contacto</a></li>
<li><a href="#menu" title="Menú">Más cosas</a></li>
</ul>
</div>

Alternativas para mostrar y esconder un div con javascript:
Showing and Hiding a DIV using CSS and Javascript - netlobo.com
domCollapse
Artículos CSS / Hojas de estilo - Capas visibles e invisibles
JS Popups with Computed Absolute Positioning
Modded Up: Slide In, Slide Out, ala Digg
Ryan J Lowe’s Dev Blog » Blog Archive » LITBox

Technorati tags: , , , ,

to Javascript... Comentarios (0)... 20 Noviembre 2006

Técnicas de esquinas redondeadas

CSS e imágenes:
Juglar :: Caja con esquinas redondeadas
The ThrashBox™
Bullet-Proof Rounded Corners
CSS Rounded Corners example
Rounded corners and shadowed boxes (W3C)
Caótico Neutral » Redondeando esquinas (I)
Caótico Neutral » Redondeando esquinas (II)
Alsacreations, Create a rounded block with CSS and XHTML
Boxless boxes | 1976design.com
A List Apart: Creating Custom Corners & Borders
A List Apart: Creating Custom Corners & Borders Part II
CSS and Round Corners: Build Boxes with Curves [CSS Tutorials]
Round Corners
Rounding Tab Corners (Complex Spiral Consulting)
CSS Teaser Box, flexible width and height | Lab | 456 Berea Street
Flexible box with custom corners and borders | Lab | 456 Berea Street
A List Apart: Articles: Mountaintop Corners
Airtight Corners
Rounded corners in CSS :: Adam Kalsey
CSS and round corners: Borders with curves
Round corners in pure css for liquid design and transparent scrolling
MODx Content Management System | Simple Rounded Corner CSS Boxes
SitePoint Tools : Spanky Corners
ervdesign » Esquinas redondas con CSS, a gusto del consumidor
ervdesign » Esquinas redondas con CSS, ancho variable

Sólo CSS sin imágenes:
Rounded Corners Without Images
stu nicholls | snazzy borders
Cool trick: rounded boxes using CSS - and NO images! - GoTutorials Forums
WebEstilo: Esquinas redondeadas sin imagenes
Follow the Arrow

Javascript sin imágenes:
Nifty Corners
More Nifty Corners - Webdesign.HTML.it
Tutorial de Nifty Corners Cube - esquinas redondeadas con CSS y JavaScript
Demo of MochiKit Visual Elements
Editsite.net - Rounded corners
Anti-aliased Nifty Corners - Acko.net - Steven Wittens
Rounded corners without images: A Nifty Corners Inspiration :: Seky
curvyCorners - JavaScript Rounded Corners and more.
Dragon Labs | The Octopus Engine
curvyCorners - Ultimate Rounded Corners.
Transcorners — Cornerus Pride is there *scared*

Javascript con imágenes:
Transparent rounded/custom corners and borders | Lab | 456 Berea Street
TCCB v2 demo page | 456 Berea Street
Alex Sancho : Esquinas personalizadas con javascript

Varias opciones:
Corners - Nested divs revisited
Bords arrondis en XHTML/CSS

Otras esquinas:
Dynamic Drive CSS Library- Curly Corner Container
a.css, esbudellant estàndards » Técnica de Esquinas Personalizadas
How to Add Fluid Borders to Your Boxes with CSS - WebReference.com
JQuery Corner Demo

Generadores automáticos:
Generador de cajas con borde redondeado en CSS
Jalenack’s Complete Rounded Corners Creator
Spiffy Corners
Spiffy Box
Cornershop

Ver también:
CSS Rounded Corners ‘Roundup’ | Smiley Cat Web Design

to CSS, Javascript... Comentarios (2)... 2 Julio 2006

Imágenes y Javascript

to Imagen, Javascript... Comentarios (8)... 30 Junio 2006

Citas aleatorias

citas
Para mostrar una cita aleatoria en Blogsome, solo copia lo siguiente en tu index, sustituyendo cada “fraseX” por una cita.

Blogsome Forum - Random taglines?
Intenta - Citas aleatorias con Javascript
Mostrar un enlace aleatorio con Javascript en Intenta

<div id="cita">{literal}
<script type="text/javascript" language="JavaScript">
<!--
function random_text()
{};
var random_text = new random_text();
var number = 0;
random_text[number++] = "frase1"
random_text[number++] = "frase2"
random_text[number++] = "frase3"
random_text[number++] = "frase4"
random_text[number++] = "frase5"
random_text[number++] = "frase6"
var random_number = Math.floor(Math.random() * number);
document.write(random_text[random_number]);
--></script>{/literal}
</div>

to Javascript, Blogsome... Comentarios (3)... 27 Mayo 2006

Introducción a AJAX

to Javascript... Comentarios (2)... 15 Mayo 2006

Diseños alternativos

to CSS, Javascript... Comentarios (5)... 9 Mayo 2006

Cambiar el tamaño de la letra

tamaño letra

En la hoja de estilos, deberíamos definir los tamaños de las fuentes (font-size) mediante unidades relativas (em, %), en vez de fijas (px, pt), si queremos que sean los usuarios los que puedan modificar el tamaño del texto a su antojo, mediante las funciones que para esta casuística disponen los navegadores. Por defecto, los navegadores suelen desplegar 16px.

Esta postura es la defiende uno de los principios de la accesibilidad:
“3.4 Utilice unidades relativas en lugar de absolutas al especificar los valores en los atributos de los marcadores de lenguaje y en los valores de las propiedades de las hojas de estilo.”

Ejemplos de funciones para modificar el tamaño del texto en navegadores:
- Firefox (versión 1.5.0.2): Herramientas - Opciones - Contenido - Tipografía
- Internet Explorer (versión 6.0): Ver - Tamaño de texto

La otra postura sería definir unas medidas fijas para las fuentes y permitir que el usuario pueda agrandar o disminuir el tamaño del texto pero desde funciones javascript predeterminadas en el diseño de la web (mediante botones, por ejemplo). Podría decirse que es la opción elegida por los que tienen un especial interés por controlar cómo se visualiza su diseño.

Para implementar botones que cambien el tamaño del texto:
Cambiar el tamaño de letra dinámicamente » Sentido Web
A List Apart: Power To The People: Relative Font Sizes
Zoom Zoom Zoom | Delta Tango Bravo
NoFunc · Dynamic Fonts
Aumentar el tamaño de un texto con Javascript en Intenta

Vease otra reflexión: Úsalo » Botones para cambiar el tamaño de letra

Útil:
A List Apart: Articles: Text-Resize Detection

to CSS, Javascript... Comentarios (2)... 7 Mayo 2006

Tiempo de lectura de un post

A propuesta del Pato-lógico, una utilidad para mostrar el tiempo aproximado de lectura cada artículo del blog. Observad su artículo para el caso Blogger. A continuación los pasos para Blogsome (ver su demo):

Guardar el siguiente archivo javascript palabra.js, o bien insertarlo directamente en el head:
<script type="text/javascript">
function tlectura(idpost,idtlectura) {
var txt = document.getElementById(idpost).innerHTML;
var ppmin = 250;
if (txt){
txt = txt.replace(/< [^>]+>/g, ” “);
var palabras = txt.match(/(\w|�|�|�|�|�|�|�|�|�|�|�|�|�)+[\s\n\r\t,\.;:”‘\(\)\{\}\[\]$]*/g);
var palabrapost = 0;
if (palabras) {palabrapost = palabras.length;}
if (palabrapost < = 8) {
document.getElementById(idtlectura).innerHTML='‘+”Tiempo lectura: Menos de 2 segundos”+’< '+'/sp'+'an>‘;
} else {
xminutos = parseInt(palabrapost/ppmin);
xsegundos = Math.round(60 * (palabrapost/ppmin - xminutos));
document.getElementById(idtlectura).innerHTML=’‘+”Tiempo lectura: “+((xminutos>0)?xminutos:”")+((xminutos>0)?((xminutos == 1)?” minuto “:” minutos “):”")+((xsegundos>0)?xsegundos:”")+((xsegundos>0)?((xsegundos == 1)?” segundo”:” segundos”):”")+’ < '+'/sp'+'an>‘;
}
}
}
</script>

En el apartado post de la plantilla:
- Identificar cada artículo con el atributo:
id="j{the_ID}"
Que podría quedar por ejemplo (según la plantilla):
<div id="j{the_ID}">
ó
<div class="post" id="j{the_ID}">

- Añadir la llamada al script que cuenta las palabras:
<script type="text/javascript">tlectura("j{the_ID}","elposttlec{the_ID}");</script>

- Donde queramos desplegar el texto del tiempo de lectura del artículo:
<span class="tlectura" id="elposttlec{the_ID}"></span>

to Blogs, Javascript, Blogsome... Comentarios (4)... 21 Marzo 2006

Slide navigation - Menú deslizante

Mini Slide Navigation es un menú horizontal que mediante javascript introduce un atractivo borde inferior deslizante.

1.- Tenemos un menú en forma de lista, tal que así:
<ul id="navheader">
<li id="home"><a href="#" title="Home">Home</a></li>
<li id="portfolio"><a href="#" title="Portfolio">Portfolio</a></li>
<li id="methodology"><a href="#" title="Methodology">Methodology</a></li>
<li id="prices"><a href="#" title="Prices">Prices</a></li>
<li id="contact"><a href="#" title="Contact">Contact</a></li>
</ul>

2.- Archivo javascript a guardar en nuestro servidor:
/******************************************************
Focus Slide
version 1.0
last revision: 12.17.2004
steve@slayeroffice.com
Should you improve upon or
modify this code, please let me know
so that I can update the version hosted
at slayeroffice.
PLEASE LEAVE THIS NOTICE INTACT!
******************************************************/
window.onload = init;
var d=document; // shortcut reference to the document object
var activeLI = 0; // the currently "active" list element - value represents its index in the liObj array
var zInterval = null; // interval variable
var SLIDE_STEP = 10; // how many pixels to move the sliding div at a time
var SLIDER_WIDTH = 80; // the width of the sliding div. used to calculate its left based on the width and left of the active LI element
function init() {
// bail out if this is an older browser or Opera which gets the offsets wrong
// the opera issue is fixable by subtracting the container UL's width from the offsetLefts...but I dont care enough to do it
// this does NOT break opera, it just wont get the sliding thing
if(!document.getElementById || window.opera)return;
// create references to the LI's
mObj = d.getElementById("navheader");
liObj = mObj.getElementsByTagName("li");
// set up the mouse over events
for(i=0;i
liObj[i].xid = i;
liObj[i].onmouseover = function() { initSlide(this.xid); }
}
// create the slider object
slideObj = mObj.appendChild(d.createElement("div"));
slideObj.id = "slider";
// position the slider over the first LI
x = liObj[activeLI].offsetLeft + (liObj[activeLI].offsetWidth/3 - SLIDER_WIDTH/3)-5;
y = liObj[activeLI].offsetTop-3;
slideObj.style.top = y + "px";
slideObj.style.left = x + "px";
}
function initSlide(objIndex) {
// return if the user is mousing over the currently active LI
if(objIndex == activeLI)return;
// clear the interval so we can start it over in a few lines to avoid doubling up on intervals
clearInterval(zInterval);
// set the active list item to the object index argument
activeLI = objIndex;
// figure out the destination for the sliding div element
destinationX = Math.floor(liObj[activeLI].offsetLeft + (liObj[activeLI].offsetWidth/3 - SLIDER_WIDTH/3))-5;
// start the interval
intervalMethod = function() { doSlide(destinationX); }
zInterval = setInterval(intervalMethod,10);
}
function doSlide(dX) {
// get the current left of the sliding div
x = slideObj.offsetLeft;
if(x+SLIDE_STEP // div is less than its destination, move it to the right
x+=SLIDE_STEP;
slideObj.style.left = x + "px";
} else if (x-SLIDE_STEP>dX) {
// div is more than its destination, move to the left
x-=SLIDE_STEP;
slideObj.style.left = x + “px”;
} else {
// div is within the boundaries of its destination. put it where its supposed to be
// and clear the interval
slideObj.style.left = dX + “px”;
clearInterval(zInterval);
zInterval = null;
}
}

(En servicios de alojamiento gratuítos (como el mío, Blogsome), que no permiten almacenar archivos javascript pero sí imágenes, podemos subirlos cambiando la extensión al archivo (.js por .jpg).)

3.- Código CSS para incluir en nuestra hoja de estilos, fácilmente personalizable:
/*-----------
www.sgclark.com
Stephen Clark
Mini-Slide Navigation - www.sgclark.com/sandbox/minislide
Last Updated: 1/28/2006
Inspired by Simplebits MiniTab Nav, and SlayerOffice Focus Slide Nav
------------*/
#navheader {
position:relative;
margin:0 auto;
width:100%;
height:18px;
border-top:1px solid #fff;
border-bottom:1px solid #78919B;
background-color:#ffffff;
padding:6px 0 0 0;
z-index:0;
}
#navheader li {
position:relative;
display:inline;
font:10px verdana;
padding:0;
z-index:20;
display : block;
float : left;
}
#navheader li a {
text-decoration:none;
color:#000000;
display : block;
text-align : center;
width : 80px;
}
#navheader li a:hover {
text-decoration:none;
color:#999999;
cursor: hand;
}
#slider {
position:absolute;
border-bottom:5px solid #78919B;
width:80px;
height:16px;
margin:0 2px 0 2px 0;
z-index:2;
margin-left : 5px;
}
/*---- Navigation Page Indicators ----*/
body#minislide li#home {
border-bottom: 5px solid #cccccc;
color:#999999;
height:13px;
width:80px;
z-index:1;
}

4.- Finalmente, introducir en la plantilla (entre los head) la llamada al archivo javascript que hemos guardado en el servidor:
<script type="text/javascript" src="/scripts/focus_slide.js"></script>

to CSS, Javascript... Comentarios (2)... 7 Marzo 2006

Imagen aleatoria

Para que cambie una imagen por otra cada vez que se recarga la página.

<script type="text/javascript">
<!-- //
var prefix = "<img src=\"";
var postfix = "\" />";
var rnumb = "";
var img = "";
rnumb += Math.floor(Math.random()*4);
img = rnumb;
if (img == "0") {
document.write(prefix+ "image1.jpg" +postfix);
}
if (img == "1") {
document.write(prefix+ "image2.jpg" +postfix);
}
if (img == "2") {
document.write(prefix+ "image3.jpg" +postfix);
}
if (img == "3") {
document.write(prefix+ "image4.jpg" +postfix);
}
// -->
</script>

Javascript Image Randomizer - Blogsome

También:
Webmaster Libre » Imágenes aleatorias con Javascript

to Imagen, Javascript... Comentarios (2)... 21 Diciembre 2005