<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Polar Geek &#187; Tutoriales</title>
	<atom:link href="http://www.polargeek.net/category/tutoriales/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.polargeek.net</link>
	<description>Desarrollo web, tips, diseño, php, javascript...</description>
	<lastBuildDate>Thu, 29 Jul 2010 09:33:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Cómo crear un plugin en jQuery</title>
		<link>http://www.polargeek.net/como-crear-un-plugin-en-jquery/</link>
		<comments>http://www.polargeek.net/como-crear-un-plugin-en-jquery/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 06:00:21 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1705</guid>
		<description><![CDATA[Hoy construiremos un plugin en jQuery, por supuesto iremos paso a paso y si no has construido nunca ninguno al final del tutorial te aseguro que podrás. ¿Empezamos? ¿Para qué sirve un plugin de jQuery? Antes que nada, tenemos que saber para qué nos sirve hacer un plugin y por qué tiene ventajas sobre hacer [...]]]></description>
			<content:encoded><![CDATA[<p>Hoy construiremos un plugin en jQuery, por supuesto iremos paso a paso y si no has construido nunca ninguno al final del tutorial te aseguro que podrás. ¿Empezamos?</p>
<h2>¿Para qué sirve un plugin de jQuery?</h2>
<p>Antes que nada, tenemos que saber para qué nos sirve hacer un plugin y por qué tiene ventajas sobre hacer un par de funciones, por ejemplo. Lo primero que debemos recordar es que <strong>plug in</strong> significa <strong>conectar</strong>, es decir, haremos algo que luego podremos conectar a distintos sitios.</p>
<p>Teniendo esto en mente, nos podemos imaginar el plugin como una caja negra, que hará algo y nos devolverá el resultado (o realizará una acción simplemente).</p>
<div class="img"><img src="http://static.polargeek.net/uploads/jquery/pluginjquery.jpg" alt="Plugin jQuery" /></div>
<p>Por tanto un plugin tendrá la posibilidad de aceptar una entrada y producir un resultado, y esta &#8220;caja&#8221; que se ve en el esquema <strong>se podrá llevar a cualquier proyecto</strong>, sin ninguna modificación, aceptando allí otra salida. Esa es la clave de los plugin, que son reutilizables en cualquier sitio, sin tener que preocuparnos por cómo está hecho ni siquiera, simplemente &#8220;conectándolo&#8221; e invocándolo con datos de entrada.</p>
<p>Además, la invocación de este plugin será la misma que hacemos cuando usamos cualquier método de jQuery: </p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#caja'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">acortar</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">//acortar será el nombre del plugin</span></pre></div></div>

<h2>Nuestro primer plugin</h2>
<h3>Qué vamos a hacer</h3>
<p>Este plugin reducirá el texto en una caja, y con un click en un enlace lo expandirá. Así de simple, aunque como veremos después la implementación va a ser un pelín más larga de lo que debería para ser nuestro primer plugin, pero sin problema, poco a poco lo haremos. Si te quedan dudas sobre qué vamos a hacer tienes un enlace al demo <a href="http://www.polargeek.net/wp-content/uploads/demos/plugin/index.html">aquí</a> y al final del post.</p>
<h3>Primeros pasos al construir un plugin</h3>
<p>Cuando se construye un plugin hay una serie de pasos generales, que se hacen para todos los plugin que construyamos y que son los siguientes:</p>
<h4>Declaración del plugin</h4>
<p>El primer paso al hacer un plugin es declararlo, extender la serie de métodos que tiene jQuery originalmente. Para ello escribimos lo siguiente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  $.<span style="color: #660066;">fn</span>.<span style="color: #660066;">acortar</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>jQuery<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Línea 1</strong>. Pasamos a nuestra declaración &#8220;jQuery&#8221;, el objeto, de tal forma que lo podemos usar como $, sin que interfiera con otras librerías.</p>
<p><strong>Línea 2</strong>. Extendemos el objeto jQuery con nuevo método llamado acortar.</p>
<p><strong>Línea 3</strong>. Recorremos todos los objetos que se le pasen a nuestro plugin. Recordemos que un selector puede seleccionar varios elementos, como todos los h1, por ejemplo. Aquí los recorremos y aplicamos la función que hagamos en nuestro plugin a cada uno de ellos.</p>
<p>Esto lo vamos a tener que hacer para todos los plugins que programemos, así que intenta entederlo bien. Lógicamente, cambiaremos el nombre dependiendo del plugin, en este caso lo llamaremos &#8220;acortar&#8221;.</p>
<h4>Parámetros que aceptaremos como opciones del plugin</h4>
<p>Casi todos los plugin tienen opciones, si estamos realizando un plugin que acorte el texto de una caja para que no se vea tan grande algunos parámetros que tenemos que permitir configurar al usuario pueden ser los siguientes:</p>
<ul>
<li>nCaracteres: Número de caracteres a mostrar. Ocultaremos el resto.</li>
<li>nExtra: Para evitar acortar un texto sólo por unos caracteres. El número exacto es este parámetro.</li>
<li>textoSuspense: String que se mostrará para hacer notar que hay más texto.</li>
<li>textoContraer: Texto mostrado como link para contraer.</li>
<li>linkExpandir: Texto mostrado como link para expandir</li>
</ul>
<p>Así el usuario podrá personalizar el plugin sin tener que preocuparse de cómo está hecho por dentro. Empecemos por procesar la entrada:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  $.<span style="color: #660066;">fn</span>.<span style="color: #660066;">acortar</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>opciones<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #003366; font-weight: bold;">var</span> parametrosPorDefecto <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	  nCaracteres<span style="color: #339933;">:</span> <span style="color: #CC0000;">300</span><span style="color: #339933;">,</span>
	  nExtra<span style="color: #339933;">:</span> <span style="color: #CC0000;">20</span><span style="color: #339933;">,</span>
	  textoSuspense<span style="color: #339933;">:</span> <span style="color: #3366CC;">'...'</span><span style="color: #339933;">,</span>
	  textoContraer<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Contrae'</span><span style="color: #339933;">,</span>
	  linkExpandir<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Click para Expandir'</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>                   
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> opciones <span style="color: #339933;">=</span> $.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>parametrosPorDefecto<span style="color: #339933;">,</span> opciones<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>jQuery<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Por tanto cuando tengamos que acceder a uno de los parámetros de entrada haremos, por ejemplo,  opciones.nExtra, así de simple.</p>
<h4>Copiar el objeto que nos pasan a variable local</h4>
<p>Cuando nos metemos en el bucle each, que puedes ver en la última sección de código, estamos procesando todos los elementos que han sido seleccionados al llamar el plugin. En ese preciso momento, cuando empezamos el bucle con un objeto, el objeto seleccionado está en la palabra reservada <strong>this</strong>, así que debemos guardarlo para referirnos siempre a él y no liarla cuando cambiemos el contexto (<i>scope</i>).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  $.<span style="color: #660066;">fn</span>.<span style="color: #660066;">acortar</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>opciones<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #003366; font-weight: bold;">var</span> parametrosPorDefecto <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	  nCaracteres<span style="color: #339933;">:</span> <span style="color: #CC0000;">300</span><span style="color: #339933;">,</span>
	  nExtra<span style="color: #339933;">:</span> <span style="color: #CC0000;">20</span><span style="color: #339933;">,</span>
	  textoSuspense<span style="color: #339933;">:</span> <span style="color: #3366CC;">'...'</span><span style="color: #339933;">,</span>
	  textoContraer<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Contrae'</span><span style="color: #339933;">,</span>
	  linkExpandir<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Click para Expandir'</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>                    
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> opciones <span style="color: #339933;">=</span> $.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>parametrosPorDefecto<span style="color: #339933;">,</span> opciones<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>         
	  objeto <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>jQuery<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Implementando nuestro plugin</h3>
<p>Bien, ya tenemos lo que queremos hacer, qué vamos a permitirle al usuario y cómo declarar el plugin. Empecemos ahora a implementar la funcionalidad en sí de éste. Esto por supuesto es propio de cada uno, así que intentaré no pararme demasiado en esta parte, porque, al fin y al cabo, ya sabemos crear un plugin genérico y la dificultad del resto dependerá de lo que queramos hacer.</p>
<h4>Procesar texto</h4>
<p>En este punto necesitamos ver si realmente tenemos que acortar el texto porque sobrepasa lo permitido (dado por el parámetro nCaracteres) y si es así ejecutamos toda la funcionalidad del plugin. A partir de aquí consideremos que estamos dentro del bucle que hemos mencionado antes (a partir de la línea 12 del último código). Veremos hasta los puntos suspensivos, dónde empezaremos en el siguiente punto.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> texto <span style="color: #339933;">=</span> objeto.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> longitudPermitida <span style="color: #339933;">=</span> opciones.<span style="color: #660066;">nCaracteres</span> <span style="color: #339933;">+</span> opciones.<span style="color: #660066;">nExtra</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Si tenemos un texto más corto no tenemos que hacer nada</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>texto.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> longitudPermitida<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> lugarCorte <span style="color: #339933;">=</span> texto.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">' '</span><span style="color: #339933;">,</span> opciones.<span style="color: #660066;">nCaracteres</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>lugarCorte <span style="color: #339933;">!=</span> <span style="color: #339933;">-</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">//Sacamos el texto hasta el lugar de corte</span>
    <span style="color: #003366; font-weight: bold;">var</span> str1 <span style="color: #339933;">=</span> texto.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>lugarCorte<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
	<span style="color: #006600; font-style: italic;">//Sacamos el resto del texto, que vamos a esconder</span>
  	<span style="color: #003366; font-weight: bold;">var</span> str2 <span style="color: #339933;">=</span> texto.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span>lugarCorte<span style="color: #339933;">,</span>texto.<span style="color: #660066;">length</span> <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">//Por último insertamos el enlace para ver más texto</span>
	objeto.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span>str1 <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;a href=&quot;#&quot; class=&quot;textoSuspense&quot;&gt;'</span> <span style="color: #339933;">+</span> 
				opciones.<span style="color: #660066;">textoSuspense</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/a&gt;'</span> <span style="color: #339933;">+</span> 
				<span style="color: #3366CC;">'&lt;span class=&quot;oculto&quot;&gt;'</span> <span style="color: #339933;">+</span> str2 <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/span&gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">//Ocultamos el resto con el método hide de jQuery</span>
	$.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.oculto'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hide</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fast'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
	<span style="color: #006600; font-style: italic;">//Enlace para expandir o contraer el texto</span>
    objeto.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span>
	  <span style="color: #3366CC;">'&lt;div class=&quot;clearboth&quot;&gt;'</span> <span style="color: #339933;">+</span>
	    <span style="color: #3366CC;">'&lt;a href=&quot;#&quot; class=&quot;anchorTexto&quot;&gt;'</span> <span style="color: #339933;">+</span> opciones.<span style="color: #660066;">linkExpandir</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/a&gt;'</span> <span style="color: #339933;">+</span>
	  <span style="color: #3366CC;">'&lt;/div&gt;'</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>                                                                                      
<span style="color: #006600; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Ahora, sigamos en el siguiente apartado por donde están los puntos suspensivos (ya queda poco).</p>
<h4>Manejando el evento onClick para ampliar o reducir el texto</h4>
<p>Lo que falta por hacer es manejar que cuando se le da al link para ver más efectivamente se vea el resto del texto, además de que el texto se oculte. Hagamos esto entonces: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ... Lo anterior ...</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> ControlLink <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.anchorTexto'</span><span style="color: #339933;">,</span> objeto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> restoTexto <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.oculto'</span><span style="color: #339933;">,</span> objeto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> suspense <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.textoSuspense'</span><span style="color: #339933;">,</span> objeto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
ControlLink.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>ControlLink.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> opciones.<span style="color: #660066;">linkExpandir</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    restoTexto.<span style="color: #660066;">show</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'normal'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    ControlLink.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span>opciones.<span style="color: #660066;">textoContraer</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    suspense.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;display&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;none&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
    restoTexto.<span style="color: #660066;">hide</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'normal'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    ControlLink.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span>opciones.<span style="color: #660066;">linkExpandir</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    suspense.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;display&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;inline&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #006600; font-style: italic;">// ... Cierre de llaves abiertas antes....</span></pre></td></tr></table></div>

<p>En esta última parte vemos si tenemos el texto oculto o no. Y si está abierto cambiamos el texto al hacer click y lo ocultamos. Y viceveras si es al revés. Recuerda que estamos controlando el evento click en el enlace para expandir o contraer el texto, simplemento eso.</p>
<h3>Recapitulación</h3>
<p>Y eso es todo, hemos creado nuestro plugin que realmente funciona haciendo algo y además es configurable hasta cierto punto. Para llamarlo (puedes ver el código en el ejemplo) haremos lo siguiente, como hemos dicho al principio:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span> language<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;Javascript&quot;</span><span style="color: #339933;">&gt;</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#1'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">acortar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  	nCaracteres<span style="color: #339933;">:</span> <span style="color: #CC0000;">300</span><span style="color: #339933;">,</span>
  	nExtra<span style="color: #339933;">:</span> <span style="color: #CC0000;">20</span><span style="color: #339933;">,</span>
  	textoSuspense<span style="color: #339933;">:</span> <span style="color: #3366CC;">'...'</span><span style="color: #339933;">,</span>
  	textoContraer<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Contrae'</span><span style="color: #339933;">,</span>
  	linkExpandir<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Click para Expandir'</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></div></div>

<p>Estos son los parámetros por defecto, por tanto si se los pasamos no pasa nada, pero es sólo un ejemplo, puedes pasarle otros.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/jquery/PrimerPlugin.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/plugin/index.html" class="demo"></a>
</div>
<h2>Conclusiones</h2>
<p>Por último destacar que lo más importante es que te quedes con cómo se construye cualquier plugin, más que con la implementación en concreto que hemos realizado. Aquí dejo los sitios que han ayudado a este post, sobre todo el de Jeremy Martin, de donde he sacado la idea del plugin y lo he modificada y separado para que sea más entendible. </p>
<ul>
<li><a href="http://blog.jeremymartin.name/2008/02/jtruncate-in-action.html">Blog de Jeremy Martin</a> | Plugin original.</li>
<li><a href="http://docs.jquery.com/Core">Explicación del Core de jQuery</a> | Documentación oficial.</li>
<li><a href="http://kamikaze00x.deviantart.com/art/Dropbox-FUSION-124352929">Autor de la &#8220;caja&#8221;</a> | DevianArt</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/como-crear-un-plugin-en-jquery/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Buenas prácticas de JavaScript por Google</title>
		<link>http://www.polargeek.net/buenas-practicas-de-javascript-por-google/</link>
		<comments>http://www.polargeek.net/buenas-practicas-de-javascript-por-google/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 04:00:35 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1636</guid>
		<description><![CDATA[Introducción Javascript, como quizá ya he dicho alguna vez, es el lenguaje con mayor relación de uso y desconocimiento del mismo, y cuando falla, la gente se sorprende, a pesar de que hayan empezado a programar en JavaScript sin tener ni idea del asunto. Aquí vemos una serie de buenas prácticas traidas de Google, en [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>Javascript, como quizá ya he dicho alguna vez, es el lenguaje con mayor relación de uso y desconocimiento del mismo, y cuando falla, la gente se sorprende, a pesar de que hayan empezado a programar en JavaScript sin tener ni idea del asunto.</p>
<div class="img"><img src="http://static.polargeek.net/uploads/javascript/google_logo.png" alt="Logo Google" /></div>
<p>Aquí vemos una serie de buenas prácticas traidas de Google, en su mayoría, que nos aclararán muchas ideas y nos ayudarán a mejorar nuestro código.</p>
<h2>Buenas prácticas</h2>
<h3>Uso de la palabra var</h3>
<p>A pesar de que se puede declarar una variable dentro de una función sin var, no es recomendable, porque no está claro en que contexto podemos acceder a ella. De tal forma, que no hay colisiones de nombres entre diferentes variables.</p>
<h3>Uso de punto y coma</h3>
<p>Quizá no sepas que JavaScript tiene por defecto lo que se llama <i>implicit insertion</i>, esto significa que por defecto inserta punto y coma el solito antes de cada salto de línea. Esto, que en principio podría parecer bueno y cómodo se convierte en un auténtico dolor de cabeza en ciertos casos, como este: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">MyClass.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">myMethod</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #CC0000;">42</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #006600; font-style: italic;">// Sin punto y coma</span>
&nbsp;
<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Inicialización de variables aquí</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Declaramos un método (no nos paremos a lo de prototype, ya lo explicaré en otro post) y después usamos una función anónima, pues bien, a la función primera se le pasa la segunda como parámetro, ¿intuitivo al máximo verdad? Pues para evitarlo sólo tenemos que tener en mente que siempre tenemos que usar los puntos y comas cuando acabemos una línea.</p>
<h3>Usar objetos para tipos primitivos</h3>
<p>Si queremos tener una variable de tipo booleana, o de un tipo primitivo hacer esto puede liar bastante las cosas: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Boolean<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hi'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Intuitivamente pensaríamos que no se va a imprimir nada, pero lo cierto es que si ejecutas el código, verás el alert con el texto &#8216;hi&#8217;.</p>
<p>Por tanto cuando queramos iniciar una variable de tipo primitivo, como &#8220;Boolean&#8221;, debemos usar la siguiente sintaxis: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> Boolean<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hi'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Y ahora no veremos el &#8216;hi&#8217;. De hecho si usamos el typeof para ver el tipo de datos que tenemos podemos comprobar que lo que estábamos creando antes no era un booleano, sino un objeto.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">typeof</span> Boolean<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'boolean'</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #003366; font-weight: bold;">new</span> Boolean<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'object'</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Ambas son true, así que tienes que tener claro cuando estás haciendo una variable de tipo objeto y cuando del tipo primitivo boolean.</p>
<h3>Los estándares se deben imponer</h3>
<p>Usa funciones o métodos estándar antes que otros que no lo son, porque favoreceran la compatibilidad entre navegadores y tu código se podrá integrar en otros más fácilmente, por ejemplo es preferible usar string.charAt(3) que string[3].</p>
<h2>Reglas de Estilo</h2>
<p>En todo lenguaje hay una serie de buenas prácticas, pero también un cierto estilo que nos ayuda a poder entender mejor el código y a adquirir una serie de reglas que hacen que el código sea igual en estilos en cualquier lugar.</p>
<h3>Nombres</h3>
<p>Siempre todo junto y cuando son varias palabras pues con mayúsculas a partir de la segunda.</p>
<ul>
<li>Funciones: estoEsUnaFuncion</li>
<li>Variables: estoEsUnaVariable</li>
<li>Clases: estoEsUnaClase</li>
<li>Enumerados: enumeradoTres</li>
<li>Métodos: estoEsUnMetodo</li>
<li>Constantes: ESTO_ES_UNA_CONSTANTE</li>
</ul>
<h3>Strings</h3>
<p>Preferiblemente con &#8221; (comillas simples) en vez con &#8220;&#8221; (comillas dobles), sobre todo de cara a que cuando escribimos HTML en un string, no tenemos que &#8220;escapar&#8221; las comillas.</p>
<h3>Paréntesis</h3>
<p>Solo cuando hagan falta, por ejemplo, no uses paréntesis en operadores como delete, typeof o void, o después de palabras reservadas como return, throw, case o new.</p>
<h3>Se consciente de lo que es true o false </h3>
<p>Uno de tantos problemas tontos con los que te encuentras cuando programas en JavaScript es asumir que ciertas cosas son verdaderas o falsas. Aquí tienes una lista: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">null</span> <span style="color: #006600; font-style: italic;">//false</span>
undefined  <span style="color: #006600; font-style: italic;">//false</span>
<span style="color: #3366CC;">''</span> string vacío <span style="color: #006600; font-style: italic;">//false</span>
<span style="color: #CC0000;">0</span> como número <span style="color: #006600; font-style: italic;">//false</span>
&nbsp;
<span style="color: #3366CC;">'0'</span> cero como string  <span style="color: #006600; font-style: italic;">//true</span>
<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> array vacío  <span style="color: #006600; font-style: italic;">//true</span>
<span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span> objeto vacío  <span style="color: #006600; font-style: italic;">//true</span></pre></td></tr></table></div>

<h3>Comenta con estilo</h3>
<p>Cuando se comenta el código además de hacer la razón por la que hacemos algo tenemos la posibilidad de generar documentación a la vez de manera sencilla, siguiendo una serie de reglas. Google lo hace así, y muchos desarrolladores lo recomiendan, en concreto podemos usar <a href="http://code.google.com/p/jsdoc-toolkit/">JSDoc</a>, y si todos lo hiciéramos sería más sencillo leer el código de otros y entenderlo, así que adelante con ello.</p>
<h2>Más información</h2>
<p>Tienes más consejos y buenas prácticas <a href="http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Visibility__private_and_protected_fields_">aquí</a>, hay muchos más, solo he destacado los más importantes y relativamente fáciles de explicar para no irme mucho del tema.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/buenas-practicas-de-javascript-por-google/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>¿Qué son los microformatos?</title>
		<link>http://www.polargeek.net/%c2%bfque-son-los-microformatos/</link>
		<comments>http://www.polargeek.net/%c2%bfque-son-los-microformatos/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 20:33:42 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Otros]]></category>
		<category><![CDATA[microformatos]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1625</guid>
		<description><![CDATA[¿Qué son los microformatos? Los microformatos son una de tantas formas que existen de dar un significado para las personas a texto plano. Normalmente se usa con HTML/XHTML, ampliando la información y dotándola de sentido para nosotros. A veces se abrevia como μF. Los usos típicos de los microformatos son coordenadas geográficas, eventos de un [...]]]></description>
			<content:encoded><![CDATA[<h2>¿Qué son los microformatos?</h2>
<div class="img"><img src="http://static.polargeek.net/uploads/microformatos/microformatos.jpg" alt="Microformatos" /></div>
<p>Los microformatos son una de tantas formas que existen de dar un significado para las personas a texto plano. Normalmente se usa con HTML/XHTML, ampliando la información y dotándola de sentido para nosotros. A veces se abrevia como μF.</p>
<p>Los usos típicos de los microformatos son coordenadas geográficas, eventos de un calendario, información de contacto&#8230;etc.</p>
<p>Los microformatos surgieron como una necesidad para hacer fácilmente reconocibles ciertos datos en Internet. Según fue creciendo la comunidad que usaba microformatos, CommerceNet (una organización que promueve el comercio electrónico) apoyó la iniciativa y contribuyó a fundar la página microformats.org, que es a dia de hoy la referencia para trabajar con microformatos.</p>
<h2>¿Por qué son importantes?</h2>
<p>Probablemente hayas oido hablar de la web semántica, que básicamente consiste en hacer que el texto plano (HTML) que forma Internet se convierta en contenido entendible por buscadores y personas respecto a lo que representan, como una dirección postal, por ejemplo. Tiene mucha más historia, que se sale del objetivo de este pequeño tutorial de introducción a los microformatos, pero la idea es esa.</p>
<p>Pues bien, los microformatos son parte de ese movimiento que facilitaría el acceso a la información por parte de la gente interesada en ella. Y lo cierto es que a pesar de lo que se pueda pensar se usan, y no han quedado como una mera idea de futuro, de hecho el 12 de Mayo de 2009 Google anunció que parsearía los microformatos hCard, HReview y hProduct (puedes ver el anuncion <a href="http://googlewebmastercentral.blogspot.com/2009/05/introducing-rich-snippets.html">aquí</a>). Este es un ejemplo del uso de microformatos que hace Google para mostrar los resultados de las búsquedas:</p>
<div class="img"><img src="http://static.polargeek.net/uploads/microformatos/ejemplomicroformatos.png" alt="Microformatos por Google" /></div>
<p>Además otras empresas como BBC también se han subido al tren de la web semántica y usan microformatos.</p>
<h2>Algunos ejemplos</h2>
<p>Veamos algunos ejemplos de código HTML usando microformatos. En este primer caso primero vemos como sería el HTML sin microformatos: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;">Lugar: 45.32, -10.05</pre></td></tr></table></div>

<p>Y usándolos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;">Lugar: 
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;geo&quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;latitude&quot;</span>&gt;</span>45.32<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;</span>,
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;longitude&quot;</span>&gt;</span>-10.05<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;</span></pre></td></tr></table></div>

<p>Como se puede ver es un poco más costoso de escribir, pero bastante básico de entender, tanto para nosotros, como para los buscadores.</p>
<p>Aquí vemos otro ejemplo más, esta vez con una tarjeta (datos de contacto), este microformato se llama hCard. Sin microformatos: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"> <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>José<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>Empresa Nueva<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>604-555-1234<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;http://ejemplo.com/&quot;</span>&gt;</span>http://ejemplo.com/<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;</span>
 <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span></pre></td></tr></table></div>

<p>Con microformatos quedaría así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"> <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;vcard&quot;</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;fn&quot;</span>&gt;</span>José<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;org&quot;</span>&gt;</span>Empresa Nueva<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;tel&quot;</span>&gt;</span>604-555-1234<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;url&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;http://ejemplo.com/&quot;</span>&gt;</span>http://ejemplo.com/<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;</span>
 <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span></pre></td></tr></table></div>

<p>Por supuesto los ejemplos sin microformatos son subjetivos, se pueden representar de mil maneras.</p>
<h2>Documentación</h2>
<p>Y por si quieres saber más sobre los microformatos aquí tienes unos enlaces muy útiles: </p>
<ul>
<li><a href="http://microformats.org/">Página oficial de los microformatos</a> (incluye generador de html con distintos microformatos)</li>
<li><a href="http://en.wikipedia.org/wiki/Microformat">Artículo de la wikipedia</a>.</li>
<li><a href="http://www.hellogoogle.com/que-son-los-microformatos-y-como-utilizarlos/">Artículo de microformatos centrado en SEO</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/%c2%bfque-son-los-microformatos/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Crear efecto spotlight con jQuery</title>
		<link>http://www.polargeek.net/crear-efecto-spotlight-con-jquery/</link>
		<comments>http://www.polargeek.net/crear-efecto-spotlight-con-jquery/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 05:00:08 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[spotlight]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1608</guid>
		<description><![CDATA[Introducción El efecto spotlight, literalmente efecto foco, consiste en un sencillo truco para captar toda la atención del usuario en un elemento de la página en la que estamos. Es un efecto muy utilizado a día de hoy, y gran parte de la culpa la tiene el hecho de que es relativamente sencillo de hacer [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>El efecto spotlight, literalmente efecto foco, consiste en un sencillo truco para captar toda la atención del usuario en un elemento de la página en la que estamos. Es un efecto muy utilizado a día de hoy, y gran parte de la culpa la tiene el hecho de que es relativamente sencillo de hacer como vamos a ver ahora mismo. Puedes ver el demo al final del post.</p>
<div class="img"><img src="http://static.polargeek.net/uploads/spotlight/capturaspotlight.jpg" alt="Spotlight Captura Demo" /></div>
<h2>Maquetado. HTML</h2>
<p>Para el HTML no nos compliquemos demasiado, simplemente usaremos una serie de imágenes cuando al pasar el ratón por encima se centre toda la atención del usuario en aquella imagen donde está situado.</p>
<p>Para ello, tendremos el siguiente código HTML:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">ul</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;listado&quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img1.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 1&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 1&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img2.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 2&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 2&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img3.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 3&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 3&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img4.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 4&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 4&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img5.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 5&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 5&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">img</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;img/img6.jpg&quot;</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 6&quot;</span> <span style="color: #000066;">alt</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;Imagen 6&quot;</span><span style="color: #66cc66;">/</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">ul</span>&gt;</span></pre></td></tr></table></div>

<p>Cómo se puede ver el maquetado es muy simple, sólo un listado con imágenes en cada elemento. Pasemos al siguiente paso.</p>
<h2>Estilos. CSS</h2>
<p>Para que esto se empiece a parecer a lo que queremos al final, necesitamos darle estilos, de tal forma que centremos el listado, y hagamos que todas las imágenes queden juntas. Para ello usamos el siguiente CSS.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
</pre></td><td class="code"><pre class="css" style="font-family:monospace;"><span style="color: #00AA00;">*</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">margin</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">padding</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
body <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">font-family</span><span style="color: #00AA00;">:</span>arial<span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin-top</span><span style="color: #00AA00;">:</span><span style="color: #933;">70px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
img <span style="color: #00AA00;">&#123;</span><span style="color: #000000; font-weight: bold;">border</span><span style="color: #00AA00;">:</span><span style="color: #993333;">none</span><span style="color: #00AA00;">;</span><span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#listado</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span><span style="color: #933;">612px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin</span><span style="color: #00AA00;">:</span><span style="color: #cc66cc;">0</span> <span style="color: #993333;">auto</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#listado</span> li <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span><span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span><span style="color: #933;">200px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span><span style="color: #933;">200px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">border</span><span style="color: #00AA00;">:</span><span style="color: #933;">2px</span> <span style="color: #993333;">solid</span> <span style="color: #cc00cc;">#666</span><span style="color: #00AA00;">;</span>	
	<span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span><span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">position</span><span style="color: #00AA00;">:</span><span style="color: #993333;">relative</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#listado</span> <span style="color: #6666ff;">.caption</span> <span style="color: #00AA00;">&#123;</span>	
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #3333ff;">:<span style="color: #993333;">none</span> </span>repeat <span style="color: #993333;">scroll</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc00cc;">#000</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span><span style="color: #993333;">none</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">:</span><span style="color: #933;">2px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">padding</span><span style="color: #00AA00;">:</span><span style="color: #933;">3px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">position</span><span style="color: #00AA00;">:</span><span style="color: #993333;">absolute</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">bottom</span><span style="color: #00AA00;">:</span><span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span><span style="color: #933;">190px</span><span style="color: #00AA00;">;</span>
	-moz-border-radius<span style="color: #00AA00;">:</span><span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
	-wekbit-border-radius<span style="color: #00AA00;">:</span><span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span><span style="color: #cc00cc;">#3c9dd7</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.clear</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">clear</span><span style="color: #00AA00;">:</span><span style="color: #993333;">both</span><span style="color: #00AA00;">;</span>	
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.effect</span> <span style="color: #00AA00;">&#123;</span>
	box-shadow<span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">10px</span> <span style="color: #cc00cc;">#444</span><span style="color: #00AA00;">;</span>	
	-moz-box-shadow<span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">10px</span> <span style="color: #cc00cc;">#444</span><span style="color: #00AA00;">;</span>	
	-webkit-box-shadow<span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">10px</span> <span style="color: #cc00cc;">#444</span><span style="color: #00AA00;">;</span>	
<span style="color: #00AA00;">&#125;</span></pre></td></tr></table></div>

<p>Cabe destacar el uso de dos clases, caption y effect. La clase <strong>caption</strong> es la que tendrá los elementos span, visibles cuando se pase el ratón por encima. La clase <strong>effect</strong>, por otra parte, es simplemente la aplicación de la sombra para cuando el ratón está encima, que se podría eliminar y el efecto que intentamos conseguir no se vería afectado.</p>
<h2>Funcionamiento. jQuery</h2>
<p>Por último tenemos que añadir la parte de funcionamiento usando jQuery, que cuando pasemos el ratón por encima el resto de elementos casi desaparezcan, estableciendo su opacidad (opacity) a 0.1. La clave para hacer esto es el uso de un método: siblings.</p>
<h3>El método siblings</h3>
<p>El significado es importante para ilustrar mejor lo que hace. Sibling es una palabra formal en inglés que significa hermano (como brother). Se le puede pasar un selector de manera opcional.</p>
<blockquote><p>Dado un conjunto de elementos, el método .siblings() devuelve el conjunto de todos los &#8216;hermanos&#8217; de este elemento.</p></blockquote>
<p>Veamos el ejemplo que tenemos en la <a href="http://api.jquery.com/siblings/">página de documentación</a> oficial.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">ul</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>list item 1<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>list item 2<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;third-item&quot;</span>&gt;</span>list item 3<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>list item 4<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
   <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;</span>list item 5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">ul</span>&gt;</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'li.third-item'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">siblings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'background-color'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'red'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Este código establecerá todos los elementos del listado con el fondo rojo menos el tercero. Así que como puedes ver es muy útil para hacer casi desaparecer todos los elementos menos en el que tenemos el puntero.</p>
<h3>Código jQuery</h3>
<p>Finalmente tenemos el código jQuery que establecerá la clase necesaria cuando se produzca el evento hover y la quitará cuando no, además, mostrará y ocultará el &#8220;title&#8221; cuando corresponda.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#listado li'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	title <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'title'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'&lt;span class=&quot;caption&quot;&gt;'</span> <span style="color: #339933;">+</span> title <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/span&gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'title'</span><span style="color: #339933;">,</span><span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.caption'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hide</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#listado li'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hover</span><span style="color: #009900;">&#40;</span>
	<span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">siblings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #000066;">stop</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'opacity'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'0.1'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'opacity'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'1.0'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'effect'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.caption'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">show</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	<span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.caption'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hide</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#listado'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">mouseleave</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeTo</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'100'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'1.0'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'effect'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Edito</strong>: Para impedir tener problemas con las animaciones en cola de jQuery (error del que me ha avisado <a href="http://www.blogatclock.net">jävi</a>), tenemos que añadir el método stop, de tal forma que si no se ha acabado el fadeTo, para hacer el efecto de menos a más opacidad, no interrumpa hacer el resto de elementos casi invisibles. Esto pasaba cuando se salía rápido del elemento y se volvía a entrar con el ratón, pero ya está solucionado.</p>
<h2>Conclusiones</h2>
<p>Este tutorial es bastante sencillo, pero puede ser aplicado a infinidad de cosas, la idea de la transparencia a 0.1 de todos los elementos menos uno para destacarlo o también se puede usar con divs en vez con elementos de un listado (li), cambiando el CSS, claro.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/spotlight/spotlight.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/spolight/index.html" class="demo"></a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/crear-efecto-spotlight-con-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Ejecutar scripts automáticamente con Cron</title>
		<link>http://www.polargeek.net/ejecutar-scripts-automaticamente-con-cron/</link>
		<comments>http://www.polargeek.net/ejecutar-scripts-automaticamente-con-cron/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 22:08:59 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Sistemas]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[sistemas]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1588</guid>
		<description><![CDATA[Cron es un programa, ejecutado a través de la línea de comandos, que hace que la ejecución de otros programas se haga cada cierto tiempo. Puede ser cada día, cada hora, o más específicamente, cada 2 días, 3 horas y 45 minutos, por poner un ejemplo. Normalmente se usa para programar ciertas tareas repetitivas, como [...]]]></description>
			<content:encoded><![CDATA[<p>Cron es un programa, ejecutado a través de la línea de comandos, que hace que la ejecución de otros programas se haga cada cierto tiempo. Puede ser cada día, cada hora, o más específicamente, cada 2 días, 3 horas y 45 minutos, por poner un ejemplo.</p>
<p>Normalmente se usa para programar ciertas tareas repetitivas, como puede ser una copia de respaldo de una base de datos o envíos de correos a usuarios.</p>
<h2>¿Cómo se puede usar?</h2>
<p>Pues es bien sencillo, quizá hay un detalle importante y es que debe ejecutarse en el servidor donde tengamos alojada nuestra página. Además debemos tener claro que por lo que desempeña es un <i>demon</i>, que se está siempre ejecutando, vamos.</p>
<p>Normalmente está iniciado por defecto, y se estará ejecutando si estás usando un sistema Unix/Linux, (sí, también se incluye Mac, al ser Unix). De todas formas para saber si se está ejecutando escribe lo siguiente en la línea de comandos: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ps</span> aux <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">grep</span> crond</pre></td></tr></table></div>

<p>Y debería mostrar una línea, con crond, si no la ves, tienes que añadir crond al comienzo de la ejecución, para que se ejecute siempre que se encienda el ordenador, esto depende del sistema operativo, pero normalmente ya lo tendrás funcionando, así que no te preocupes.</p>
<h2>Edición del crontab</h2>
<p>Crontab es el nombre que se le da a un archivo donde se especifica de una forma que ahora veremos los programas / scripts que se van a ejecutar y cada cuánto tiempo. Para editarlo solo tienes que ejecutar: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">crontab <span style="color: #660033;">-e</span></pre></td></tr></table></div>

<p>La sintaxis es la siguiente: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">minutos  horas  día_del_mes  mes   dia_de_la_semana &lt;comando&gt;
(0-59)   (0-23)   (1-31)    (1-12)      (0-6)</pre></td></tr></table></div>

<p>Hay que tener en cuenta que la semana empieza en Domingo, así que 0 en el día de la semana será cada Domingo. De todas formas veamos algún ejemplo para que quede claro: </p>
<p>Cada día a una hora determinada (23:15)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">15</span> <span style="color: #000000;">23</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<p>Cada mes (día 25) a una hora determinada (20:00)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">0</span> <span style="color: #000000;">20</span> <span style="color: #000000;">25</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<p>Los viernes a las 15:00</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">0</span> <span style="color: #000000;">15</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000; font-weight: bold;">*</span> <span style="color: #000000;">5</span> <span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<h4>Valores predefinidos</h4>
<p>En esta tabla de la wikipedia se puede ver la serie de valores predefinidos para facilitarnos un poco la vida.</p>
<p><img src="http://static.polargeek.net/uploads/cron/crontabla.jpg" alt="Tabla Cron Valores Predefinidos"/></p>
<p>Cada vez que reiniciemos el servidor</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">@</span>reboot <span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<p>Y podríamos hacer muchos más, lo que hay que tener claro es una regla sencilla, <strong>lo que se quede con asterisco, se hará cada vez que el campo especifica</strong>, es decir si dejamos con asterisco los minutos se hará todos los minutos, si dejamos las horas se hará todas las horas.</p>
<p>Por supuesto los días del mes y de la semana entran en conflicto, es decir que si especificas uno, pues el asterisco del otro no se toma como &#8220;todos&#8221;, por ejemplo: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">0</span> <span style="color: #000000;">10</span> <span style="color: #000000;">20</span> <span style="color: #000000;">2</span> <span style="color: #000000;">0</span> <span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></td></tr></table></div>

<p>Esto se ejecutará Los días 20 de Febrero a las 10:00 que sean Domingos, es decir que no será todo los años, solo los años en que el 20 de Febrero caiga en Domingo. Así que hay que tener cuidado.</p>
<h2>Uso con script de PHP</h2>
<p>Veo necesario mostar un ejemplo con PHP, que hará que se ejecute cada cierto tiempo teniendo la salida en otro archivo (log) para controlar lo que pasa. En primer lugar editamos un archivo php (ejemplo.php): </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$fecha</span> <span style="color: #339933;">=</span> <span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'d \d\e\l m \d\e Y \a \l\a\s H:i'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Ejecutado el &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$fecha</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>	
&nbsp;
<span style="color: #666666; font-style: italic;">//Salida: Ejecutado el 01 del 07 de 2010 a las 16:35</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Como puedes ver depende de la hora y fecha en la que estemos así para cada minuto tendremos una salida distinta. Es sólo un ejemplo, pero podría ser un backup de una base de datos o el envío de 500 correos con un mensaje de salida.</p>
<p>Ahora, para ejecutarlo, tenemos que tener claro que los scripts de PHP no son ejecutables si PHP está en modo CGI en el servidor, que suele pasar, por tanto tenemos que buscar el comando que los ejecuta, para ello en el terminal ponemos: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">which</span> php</pre></td></tr></table></div>

<p>En mi caso es /usr/bin/php, así que el comando a ejecutar por el cron será: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>php <span style="color: #000000; font-weight: bold;">/</span>ruta<span style="color: #000000; font-weight: bold;">/</span>a<span style="color: #000000; font-weight: bold;">/</span>script<span style="color: #000000; font-weight: bold;">/</span>ejemplo.php</pre></td></tr></table></div>

<p>Además queremos tener la salida en un archivo log: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>php <span style="color: #000000; font-weight: bold;">/</span>ruta<span style="color: #000000; font-weight: bold;">/</span>a<span style="color: #000000; font-weight: bold;">/</span>script<span style="color: #000000; font-weight: bold;">/</span>ejemplo.php <span style="color: #000000; font-weight: bold;">&gt;&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>ruta<span style="color: #000000; font-weight: bold;">/</span>a<span style="color: #000000; font-weight: bold;">/</span>logs<span style="color: #000000; font-weight: bold;">/</span>log.txt</pre></td></tr></table></div>

<p>Por tanto cuando ejecutando esto en el terminal <strong>a mano</strong> cada minuto obtenemos un archivo con algo como: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">Ejecutado el 01 del 07 de 2010 a las 16:57
Ejecutado el 01 del 07 de 2010 a las 16:58
Ejecutado el 01 del 07 de 2010 a las 16:59
Ejecutado el 01 del 07 de 2010 a las 17:00</pre></td></tr></table></div>

<p>Pues bien una vez que tenemos nuestro comando funcionando lo único que tenemos que hacer es editar el crontab para que se ejecute el solo. Para ello ejecutamos crontab -e, como hemos dicho antes y llegaremos a un editor de texto en terminal, allí pondremos: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="text" style="font-family:monospace;"># esto es un comentario
&nbsp;
# script de prueba
15 15 * * * /usr/bin/php /ruta/a/script/ejemplo.php &gt;&gt; /ruta/a/logs/log.txt</pre></td></tr></table></div>

<p>Esto se ejecutará todos los días a las 15:15, así que el log se irá llenando poco a poco, una línea por día.</p>
<h2>Interfaces de Usuario para Cron</h2>
<p>Además de editar el archivo a mano hay una serie de interfaces, normalmente de las propias compañías de Hosting, que facilitan la tarea con un menú. Pero no siempre tenemos estas herramientas así que es mejor aprenderse bien la sintaxis y si luego las tenemos pues mejor. Esta imagen corresponde al panel que hay en Dreamhost.</p>
<p><img src="http://static.polargeek.net/uploads/cron/cronDreamhost.jpg" alt="Cron en Dreamhost"/></p>
<h2>Conclusión</h2>
<p>Cron es una herramienta muy útil, como has podido ver, y además se usa a día de hoy en casi todos los servidores del mundo para hacer tareas de mantenimiento o de la propia aplicación web que está funcionando allí. Aquí dejo un par de enlaces para más información:</p>
<ul>
<li><a href="http://es.wikipedia.org/wiki/Cron_%28Unix%29">Artículo de la wikipedia</a> (muy completo).</li>
<li><a href="http://www.linuxtotal.com.mx/index.php?cont=info_admon_006">Manual de Cron</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/ejecutar-scripts-automaticamente-con-cron/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diferencias entre GET y POST de HTTP</title>
		<link>http://www.polargeek.net/diferencias-entre-get-y-post-de-http/</link>
		<comments>http://www.polargeek.net/diferencias-entre-get-y-post-de-http/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 06:15:36 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Otros]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[POST]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1576</guid>
		<description><![CDATA[¿Qué es GET y POST? Probablemente hayas oído alguna vez de GET y POST sin entender muy bien lo que es. Intentemos aclarar eso antes de entrar en sus diferencias. Tanto GET como POST son métodos de HTTP. Esto no es algo que es así y ya, sino que se propusieron, fueron aceptados y a [...]]]></description>
			<content:encoded><![CDATA[<h2>¿Qué es GET y POST?</h2>
<p>Probablemente hayas oído alguna vez de GET y POST sin entender muy bien lo que es. Intentemos aclarar eso antes de entrar en sus diferencias.</p>
<p>Tanto GET como POST son métodos de HTTP. Esto no es algo que es así y ya, sino que se propusieron, fueron aceptados y a día de hoy los utilizamos constántemente, podría haber sido de otra forma, porque, como cualquier protocolo (tanto de la vida como la informática) es sólo un convenio. Para entender un poco más mira el siguiente esquema.</p>
<p><img src="http://static.polargeek.net/uploads/getpost/ejemplo_get.jpg" alt="Ejemplo GET" title="Ejemplo GET"/></p>
<p>Como se puede ver el usuario hace click en un enlace y Firefox, o el navegador que sea, traduce esa acción en la petición de la página al servidor. Pues bien, en esa petición se utiliza GET. Así que es simplemente una manera de decirle al servidor que haga algo, en este caso que le de index.html para mostrárselo al usuario.</p>
<h2>Método GET</h2>
<p>Como acabamos de ver GET pide un recurso a un servidor y éste se lo devuelve si lo tiene y puede, o si no da un mensaje de error. No es la intención del tutorial meterse con los mensajes de error, pero como repuesta el GET el servidor da un mensaje 200 si ha ido bien, y si no encuentra lo que pides da un 404, si no sabías de donde venía lo del famoso error 404 aquí lo tienes, es sólo una respuesta a GET.</p>
<p>Lo cierto es que no necesitamos hacer a mano una petición GET, por lo que no tenemos que sabernos su sintaxis, ya lo hacen los navegadores por nosotros, pero para que veas lo sencillo que puede ser mira el siguiente código:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">	GET <span style="color: #000000; font-weight: bold;">/</span>index.html HTTP<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.1</span>
	Host: www.ejemplo.com</pre></td></tr></table></div>

<p>Lo de después de HTTP es la versión del protocolo, pero básicamente esto le llega al servidor y &#8220;entiende&#8221; que tiene que devolver index.html. Como puedes imaginar esto no es lo único que mandamos cuando pedimos una página, también mandamos muchos de nuestros datos, desde la codificación de caracteres aceptada, hasta que navegador y sistema operativo usamos. De esa forma el servidor puede hacer una cosa u otra (además de saber a quién tiene que responder, claro). Hay 30 cabeceras (de solicitud) que acepta HTTP, estas son algunas de ellas:</p>
<ul>
<li><strong>Accept</strong>. Tipos de datos compatibles, como text/plain.</li>
<li><strong>Accept-Charset</strong>. Codificación de caracteres que acepta el navegador.</li>
<li><strong>Accept-Encoding</strong>. Que codificaciones de archivos acepta, como gzip.</li>
<li><strong>Cookie</strong>. Envía la cookie si ha sido preestablecida antes por el servidor.</li>
<li><strong>Host</strong>. A dónde se hace la petición, como www.ejemplo.com.</li>
<li><strong>User-Agent</strong>. Aquí se envía el navegador, la versión y el sistema operativo.</li>
<li><strong>Date</strong>. Fecha y hora en la que se produce la petición.</li>
</ul>
<p>Además hay otras cabeceras de respuesta, que el servidor da al cliente, como Server, que indica que servidor es o Set-Cookie, que contiene una cookie para que el navegador la guarde.</p>
<p>En principio se considera que GET es un método seguro, puesto que no afecta al servidor en el sentido de que no cambia nada que tenga, simplemente le pide un recurso y éste se lo da o no. Esa es la principal razón por la que los robots de Google y otros buscadores utilizan este método para analizar Internet.</p>
<h2>Método POST</h2>
<p>Este método se utiliza mucho también, pero no de la misma forma. Cuando a un servidor le llega un mensaje de POST, analiza el mensaje porque el cliente le ha enviado datos, no solo la URL de lo que quiere más las cabeceras.</p>
<p>Este método se utiliza para subir un archivo a una página, o enviar ciertos datos a través de un formulario, aunque de esto discuteremos después.</p>
<p>Lo importante que nos debe quedar claro, es que si bien GET está pensado para solicitar un recurso, POST está pensado para mandar &#8220;algo&#8221; al servidor aparte de decirle lo que queremos.</p>
<p>Además, tenemos que pensar en que si el servidor está bien programado el resultado de hacer una petición POST cambiará su estado, la palabra técnica es que no es idempotente, es decir, que si se hace otra vez, el servidor va a cambiar de alguna forma. Para que quede más claro echa un vistazo al siguiente esquema: </p>
<p><img src="http://static.polargeek.net/uploads/getpost/ejemplo_post.jpg" alt="Ejemplo POST" title="Ejemplo POST"/></p>
<p>Este esquema representa lo que pasa, de manera simplificada, cuando un usuario hace un comentario en un blog con WordPress. Este comentario es enviado a través del método POST y cuando llega el servidor lo almacena en la base de datos. Si se enviara de nuevo el comentario esto afectaría a la base de datos, que tendria otro comentario más.</p>
<h2>Pero entonces&#8230;¿GET o POST?</h2>
<h3>Cuando la operación es idempotente -> GET</h3>
<p>Como hemos explicado antes idempotente significa que a pesar de que se repita la operación no cambia el estado del servidor.</p>
<p>Por ejemplo: entrar a google.com y al rato entrar de nuevo no cambia nada en los servidores de Google. En cambio si nos registramos si cambia, puesto que en alguna parte de su base de datos noSQL (BigTable, se llama), tendremos un nuevo registro.</p>
<h3>Formularios y operaciones no idempotentes -> POST</h3>
<p>Soy de la opinión de que todos lo que queramos enviar en formularios se debe hacer a través de POST, explicaré por qué.</p>
<p>Cuando enviamos algo a <i>http://www.ejemplo.com/post.php</i> con POST la URL que vemos es esa, en cambio si lo enviamos con GET quedaría <i>http://www.ejemplo.com/post.php?campo1=contenido&#038;campo2=contenido2</i>, por ejemplo, por tanto resulta más limpio a nivel del usuario y de SEO que las páginas que tengan que recibir más información además de la URL lo hagan por POST.</p>
<h2>Existen más métodos</h2>
<p>GET y POST son sólo dos de los que existen, hay algunos que casi no se utilizan y que no se conocen mucho, pero forman parte del protocolo HTTP y deberíamos, al menos, saber para qué sirven. Aquí teneís un breve resumen de cada uno:</p>
<ul>
<li><strong>HEAD</strong>. Como GET pero solo pide las cabeceras de respuesta, en vez de las cabeceras y el contenido.</li>
<li><strong>PUT</strong>. Sube al servidor un recurso, lo crea, para entendernos.</li>
<li><strong>DELETE</strong>. Borra un recurso.</li>
<li><strong>TRACE</strong>. Envía de vuelta lo recibido del cliente, para que pueda ver si servidores intermedios han alterado el contenido del mensaje.</li>
<li><strong>OPTIONS</strong>. Devuelve los métodos que soporta el servidor.</li>
<li><strong>CONNECT</strong>. Convierte la conexión actual a un tunel TCP/IP, normalmente usado para SSL.</li>
<li><strong>PATCH</strong>. El cliente solicita una serie de cambios en un recurso determinado.</li>
</ul>
<h2>Conclusiones</h2>
<p>El objetivo de este post es que quede claro lo que es una operación idempotente, y cuándo usar GET o POST, aunque hay veces que se pueden usar los dos. Aquí dejo una lista de enlaces para más información.</p>
<ul>
<li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC* de la versión 1.1 de HTTP</a>.</li>
<li><a href="http://www.cs.tut.fi/~jkorpela/forms/methods.html">Otro artículo sobre diferencias entre GET y POST</a>.</li>
<li><a href="http://carsonified.com/blog/dev/the-definitive-guide-to-get-vs-post/">Otro más sobre GET y POST</a>.</li>
<li><a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">Artículo de la wikipedia sobre HTTP</a>.</li>
<li><a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers">Listado de cabeceras de HTTP</a>.</li>
</ul>
<h4>*¿Qué es un RFC?</h4>
<p>RFC corresponde a las siglas Request For Comments (Petición de Comentarios) y, básicamente, es un documento que especifica un protocolo en Internet sin ambigüedades, que se sube a la página de RFC oficial. Lo sorprendente es que cualquiera puede hacerlo y si finalmente se acepta puede convertirse en un estándar de Internet.</p>
<p>En general son documentos llenos de detalles bastante aburridos de leer, para qué nos vamos a engañar. Aquí tenéis unos cuántos: <a href="http://www.faqs.org/rfcs/rfc793.html">TCP</a>, <a href="http://tools.ietf.org/html/rfc1812">requisitos de un Router</a> y <a href="http://tools.ietf.org/html/rfc1">el primer RFC de 1969</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/diferencias-entre-get-y-post-de-http/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mejora el rendimiento de MySQL</title>
		<link>http://www.polargeek.net/mejora-el-rendimiento-mysql/</link>
		<comments>http://www.polargeek.net/mejora-el-rendimiento-mysql/#comments</comments>
		<pubDate>Sat, 26 Jun 2010 07:22:12 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[rendimiento]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1565</guid>
		<description><![CDATA[Introducción En este post veremos como podemos mejorar el rendimiento de nuestras bases de datos MySQL de maneras realmente sencillas en su mayoría. Reducir el tiempo en consultas de MySQL puede redundar en un aumento importante en la parte del servidor. Ten en cuenta que es muy importante tomar estas medidas una cada vez, y [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>En este post veremos como podemos mejorar el rendimiento de nuestras bases de datos MySQL de maneras realmente sencillas en su mayoría. Reducir el tiempo en consultas de MySQL puede redundar en un aumento importante en la parte del servidor. Ten en cuenta que es muy importante tomar estas medidas una cada vez, y centrarse en lo que realmente reduce el tiempo de las consultas sustancialmente.</p>
<p>Suele ser mejor marcarse objetivos, como mejorar el rendimiento un 20% que hacerlo de forma descontrolada. Así que veamos punto por punto como hacerlo.</p>
<div class="img"><img src="http://static.polargeek.net/uploads/mysql_tiempo/mysql_logo.jpg" alt="Logo MySQL" /></div>
<h2>Asegúrate de seleccionar lo que necesites</h2>
<p>Cuando hagas una consulta tienes que ser consciente de que cada campo ocupa un espacio que se va a multiplicar por las filas que traigas. Nunca hagas algo como esto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SELECT</span> <span style="color: #CC0099;">*</span>
<span style="color: #990099; font-weight: bold;">FROM</span> edificios
<span style="color: #990099; font-weight: bold;">WHERE</span> nombre <span style="color: #CC0099;">=</span> <span style="color: #008000;">&quot;casa&quot;</span></pre></td></tr></table></div>

<p>Así que cada vez que hagas una consulta intenta seleccionar sólamente lo que quieras, y nada más.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SELECT</span> id<span style="color: #000033;">,</span> altura
<span style="color: #990099; font-weight: bold;">FROM</span> edificios
<span style="color: #990099; font-weight: bold;">WHERE</span> nombre <span style="color: #CC0099;">=</span> <span style="color: #008000;">&quot;casa&quot;</span></pre></td></tr></table></div>

<p>Y probablemente pienses, bueno ¿y qué pasa cuando selecciono absolutamente todos los campos? Pues que tampoco deberías utilizar el asterisco, no ya por la velocidad, sino por escribir código legible. Así que quédate con que, como regla general, es mejor no usar nunca el asterisco en los SELECT y escribir todos los campos que queremos recuperar separados por comas.</p>
<h2>Usa la caché</h2>
<p>Si haces más lecturas que escrituras deberías usar la caché, ésta proporciona una mejora en el rendimiento bastante notable. En la gráfica tienes unas pruebas de <a href="http://www.mysqlperformanceblog.com/">MySQL Performance Blog</a>.</p>
<p><img src="http://static.polargeek.net/uploads/mysql_tiempo/mysql_cache.png" alt="Caché MySQL" /></p>
<p>Por supuesto son pruebas puntuales, pero nos sirven para hacernos una idea de cuánto puede mejorar el rendimiento. Lo importante es que tengas claro que siempre que pueda la caché guardará los resultados de las consultas SELECT, para devolverlos sin tener que consultar realmente la base de datos, cuando se haga otra vez la misma consulta.</p>
<p>Puede parecer un poco raro que hagas 20 veces la misma consulta a la base de datos, pero eso es exáctamente lo que suele pasar en la mayoría de páginas en Internet. Por ejemplo si tienes una página de anuncios de coches y quieres mostrar los anuncios por ciudades, lo más normal es tener una tabla de ciudades así que harás algo como esto: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SELECT</span> nombre
<span style="color: #990099; font-weight: bold;">FROM</span> ciudades
<span style="color: #990099; font-weight: bold;">WHERE</span> pais<span style="color: #CC0099;">=</span><span style="color: #008000;">&quot;España&quot;</span></pre></td></tr></table></div>

<p>Pues bien, si entran 200 personas al día a tu página, tendrás que hacer 200 veces esta consulta si no tienes la caché funcionando. Si por el contrario la caché esta activa sólo sería 1, mientras las ciudades no cambien de nombre (que no suele pasar muy a menudo&#8230; =)).</p>
<h2>Entiende la caché</h2>
<p>Cuando tienes que usar tiempos en las consultas, algo que es muy normal, podría darse el caso de que tuvieras algo como esto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;">...<span style="color: #990099; font-weight: bold;">WHERE</span> fecha_fabricacion <span style="color: #CC0099;">&gt;=</span> <span style="color: #000099;">CURRENT_DATE</span><span style="color: #FF00FF;">&#40;</span><span style="color: #FF00FF;">&#41;</span> <span style="color: #CC0099;">-</span> <span style="color: #CC0099; font-weight: bold;">INTERVAL</span> <span style="color: #008080;">7</span> <span style="color: #9900FF; font-weight: bold;">DAY</span></pre></td></tr></table></div>

<p>Si te fijas aquí tienes una función (CURRENT_DATE) que no se puede cachear, porque a cada momento que la ejecutes vas a tener un tiempo diferente. </p>
<p><strong>Solución</strong>: pasa la fecha desde el script, ya sea PHP, Python&#8230;etc. De esa forma esa consulta que puede devolver 50 registros, se cacheará y si se hace 200 veces al día no la tendrá que hacer siempre de nuevo, lo cierto es que estamos hablando de bastante RAM ahorrada.</p>
<h2>Conoce los tipos de datos</h2>
<p>Cuando estemos creando las tablas tenemos que ser conscientes de que cada tipo de dato ocupa más o menos si se llena o no. Se que puede sonar un poco confuso, así que veamos un ejemplo concreto.</p>
<div class="img"><img src="http://static.polargeek.net/uploads/mysql_tiempo/tipos_datos_mysql.jpg" alt="Tipos Datos MySQL"/></div>
<p></p>
<p>Como puedes ver en la imagen, si vamos a almacenar un número tenemos que ver el rango en el que va a estar, de esa forma no desaprovechamos bytes. Que no es tanto por el espacio en disco, que normalmente suele sobrar, sino más por las veces que recuperemos datos de la tabla.</p>
<h2>Uso de LIMIT</h2>
<p>Es muy importante que entendamos LIMIT. Básicamente reduce al número que le pasemos lo que devuelve la consulta. Por ejemplo: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">SELECT</span> nombre
<span style="color: #990099; font-weight: bold;">WHERE</span> edad <span style="color: #CC0099;">=</span> <span style="color: #008080;">25</span>
<span style="color: #990099; font-weight: bold;">LIMIT</span> <span style="color: #008080;">1</span></pre></td></tr></table></div>

<p>Esto devolverá: un registro si tenemos en la tabla alguien con edad 25 o nada. Así, si lo que queremos mostrar es una persona en este caso el uso de LIMIT nos evita tener que sacar más registros de la base de datos cuando realmente no vamos a usarlos.</p>
<p>Por otra parte cuando vayamos a hacer un INSERT o un DELETE muy grande es mejor hacerlo poco a poco usando LIMIT, en vez de todo a la vez, y esto es porque el rendimiento del servidor entero (y por lo tanto de nuestra web de cara a los usuarios) puede verse afectado.</p>
<h2>Extra. Usa un ORM</h2>
<p>Esto es más una cuestión de facilitarnos la vida que otra cosa, pero es que realmente nos puede ayudar mucho. La idea básicamente consiste en tener una serie de clases con sus atributos y relaciones que correspondan con las tablas que tenemos en la base de datos. Haciendo algo como: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
	<span style="color: #000088;">$coche</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Coche<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$coche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">color</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;rojo&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$coche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">caballos</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">223</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$coche</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Guarda el objeto en la base de datos</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Tendremos en la base de datos una tabla coches, y cuando hacemos save() se ejecuta una consulta INSERT. Como puedes ver es muy cómodo y nos evitamos tener que hacerlo nosotros mismos en la clase o simplemente cuando establecemos los atributos. Este ejemplo es de Doctrine, pero hay otras alternativas como Propel, Qcodo o pdoMap.</p>
<p>Por supuesto en todas debes instalar el ORM para que funcione como es debido, pero la base de datos se suele generar sola, acorde con las clases que tengas, lo cual es una gran ventaja. Y lo cierto es que tienen otras muchas ventajas, que dan para un post ellas solas.</p>
<h2>Conclusión</h2>
<p>Lo cierto es que hay muchas más medidas a tomar pero estas te pueden servir como guía para empezar. En cualquier caso, si te ha interesado el tema, aquí tienes enlaces donde aprender más.</p>
<ul>
<li><a href="http://video.google.com/videoplay?docid=2524524540025172110#">Charla de Jay Pipes sobre la mejora de rendimiento con MySQL</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.0/en/query-cache.html">Documentación oficial sobre la caché de consultas de MySQL</a></li>
<li><a href="http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#PHP">Listado de ORM de PHP en la Wikipedia</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/mejora-el-rendimiento-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>¿Qué framework de PHP debería elegir?</title>
		<link>http://www.polargeek.net/que-framework-de-php-deberia-elegir/</link>
		<comments>http://www.polargeek.net/que-framework-de-php-deberia-elegir/#comments</comments>
		<pubDate>Sun, 13 Jun 2010 00:51:57 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1530</guid>
		<description><![CDATA[Características a tener en cuenta al elegir framework Probablemente casi todos los desarrolladores que eligen un framework de PHP para trabajar con él por primera vez, lo hagan sin pensar demasiado en lo que puede o no puede hacer. Quizá por una recomendación, simplemente por probar o ambas, pero al trabajar en un proyecto tenemos [...]]]></description>
			<content:encoded><![CDATA[<h2>Características a tener en cuenta al elegir framework</h2>
<p>Probablemente casi todos los desarrolladores que eligen un framework de PHP para trabajar con él por primera vez, lo hagan sin pensar demasiado en lo que puede o no puede hacer. Quizá por una recomendación, simplemente por probar o ambas, pero al trabajar en un proyecto tenemos que tener en cuenta que cosas podemos esperar de un framework y cuáles no. Veamos las característica más importantes a tener en cuenta.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/logos_frameworks.jpg" alt="Logos Frameworks" title="Logos Frameworks"/>
</div>
<h3>Módulos disponibles</h3>
<p>Casi todos los framework en PHP tienen una serie de librerías, módulos o helpers (cada uno lo llama de una forma) que básicamente consisten en una serie de funciones &#8220;extra&#8221; que tenemos disponibles para trabajar con ellas. Normalmente se agrupan en archivos, como funciones relacionadas con arrays, o funciones relacionadas con strings.</p>
<p>Un ejemplo de este tipo de funciones puede ser repeater(), del helper de strings de CodeIgniter que hace simplemente esto: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;No volveré a decir tacos en clase.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> repeater<span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>En la salida repite 5 veces la frase dada. Es una función de utilidad discutible, puesto que sustituye a un simple for de manera elegante, pero tomémoslo como un ejemplo de funciones que aportan los framework y que no tenemos que implementar. Hay algunos módulos, por ejemplo para parsear RSS, o lidiar más fácilmente con las bases de datos.</p>
<h3>Versión de PHP</h3>
<p>Quizá no parezca importante para trabajar en nuestros ordenadores, pero no siempre tenemos acceso a la última versión de PHP, así que es importante tener claro si vamos a trabajar en una versión u otra qué framework elegir.</p>
<h3>Desarrollo activo</h3>
<p>Es de suma importancia que elijas un framework que se encuentre bajo desarrollo activo. Es decir, que el autor o autores no hayan abandonado el proyecto hace tiempo. Esto es básicamente por dos razones: </p>
<ol>
<li>Cuando tengas una duda habrá desarrolladores para contestarla, interesados también en el framework. Si no estuviera bajo desarrollo, nadie se preocuparía de usarlo y no habría nadie que te pudiera ayudar.</li>
<li>El desarrollo de PHP afectará al desarrollo del framework por lo que mejorará. La implementación interna de los frameworks de PHP es, lógicamente, en PHP. Como sabrás es un lenguaje que está en un desarrollo intensísimo, y muchas funciones se convierten en <i>deprecated</i> (antiguas, que no se aconseja su uso) en poco tiempo. Si el framework está evolucionando corregirá este tipo de implementaciones con las nuevas versiones proporcionadas por PHP.</li>
</ol>
<p>A veces también conviene tener en cuenta quién está detrás de cada framework. Por ejemplo detrás del framework Zend está la empresa que fue fundada por los creadores de PHP tal y como lo conocemos hoy. Así que es casi una garantía de éxito que ese framework llegara a triunfar.</p>
<h3>Modelo Vista Controlador (MVC)</h3>
<p>Modelo Vista Controlador es un patrón de diseño que se basa en dividir la implementación en tres partes:</p>
<ul>
<li><strong>Modelo. </strong> Normalmente es la representación de la información. Si vamos a tratar con coches y hacemos una clase &#8220;coches&#8221;, esta clase será nuestra parte modelo, a grandes rasgos.</li>
<li><strong>Vista. </strong> La interfaz de usuario, en desarrollo web suele ser la propia web con el HTML y CSS.</li>
<li><strong>Controlador. </strong> El encargado de recibir acciones y actuar en consecuencia, por ejemplo, si el usuario rellena un formulario y me lo envía en controlador será el encargado de manejar esa información.</li>
</ul>
<p>Además, y sin entrar en muchas más profundidad sobre el tema para no desviarnos, hay relaciones entre estas partes, las más importantes suelen ser estas: </p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/esquema_MVC.png" alt="Esquema Modelo Vista Controlador" title="Esquema Modelo Vista Controlador"/>
</div>
<p>Por lo tanto si queremos desarrollar con este patrón tenemos que ver si el framework está orientado a él o no. Aunque te adelanto que la mayoría lo están.</p>
<h3>Curva de aprendizaje</h3>
<p>Esta no es tanto una característica interna de los framework, sino más bien una consecuencia de trabajar con ellos. Normalmente a mayor complejidad y funcionalidad más tiempo se tarda en aprenderlo. Mi consejo aquí es que si vas a tardar más tiempo aprendiendo el framework que utilizándalo estás usando el framework equivocado.</p>
<p>Es decir, el tiempo que le vayas a dedicar a aprender como usar el framework si no lo conoces, debe ser proporcional al tiempo que vaya a durar un proyecto.</p>
<h3>Necesidades propias</h3>
<p>Hay muchas más características que podríamos estudiar antes de decidirnos pero como receta general solo se puede nombrar las anteriores, básicamente, porque el resto dependerá de las necesidades del proyecto. Así que si tienes oportunidad investiga un poco más sobre cada característica que te ofrezca el framework que elijas. Porque cada uno tiene una serie de propiedades, que intentaré comparar a contuación y que lo hacen único.</p>
<h2>Comparativa de frameworks famosos</h2>
<p>Esta comparativa se basa en datos recopilados en diferentes webs y en las oficiales de los propios frameworks. He destacado ciertas características más o menos importantes, como puedes ver casi todos tienen de todo, siendo el más completo Zend Framework, pero quizá el que más tiempo se tarda en aprender, aunque esto depende mucho de la experiencia previa que tengas como programador y de la persona en sí.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/comparativa_frameworks.png" alt="Comparativa Frameworks Famosos" title="Comparativa Frameworks Famosos"/>
</div>
<p> </p>
<p>Algunas características pueden ser discutidas, puesto que se pueden conseguir instalando algo extra de manera relativamente sencilla, pero he intentado representar lo que trae el framework &#8220;de fábrica&#8221; y que realmente está listo para ser usado.</p>
<h3>Uso de módulos independientes</h3>
<p>Se ha destacado la facilidad de uso de módulos independientes sin tener que depender del resto del framework.</p>
<h3>ORM</h3>
<p>ORM (Object Relational-Maping o Mapeo objeto-relacional) es una técnica que simboliza los datos que tenemos en una base de datos con clases. De tal forma que tendremos, por ejemplo, una clase coche con los atributos X e Y y una tabla con los mismos atributos. Lo cierto es que salvo operaciones concretas no afecta demasiado al rendimiento, y facilita enormemente la programación, reduciendo líneas de código. Haré un post sobre esto en el futuro, así que no te preocupes si no lo entiendes completamente.</p>
<h2>Otras alternativas</h2>
<h3>Frameworks de PHP menos famosos</h3>
<p>Además de las alternativas mencionadas, las más famosas y utilizadas hay muchísimas más bajo desarrollo que están emergiendo y que se merecen también que le echemos un vistazo. Algunos de ellos son: <a href="http://www.pradosoft.com/">Prado</a>, <a href="http://www.yiiframework.com/">Yii</a> o <a href="http://www.akelos.org/">Akelos</a>, aunque hay muchos más.</p>
<h3>DIY (hazlo tú mismo)</h3>
<p>Hay muchos defensores de que el mejor framework que puedes usar para programar es el que te construyas tú mismo. Es decir que poco a poco crees una serie de librerías y estructuras de directorio hechas por tí y las utilices en varios proyectos.</p>
<p>En realidad es un ejercicio genial que te aconsejo encarecidamente que hagas. Te enseñará mucho de programación, pero por otra parte a veces no hay tiempo y en muchos proyectos se utilizan frameworks por el simple hecho de que están testados en muchas situaciones y el desarrollo sobre ellos en mucho más rápido.</p>
<p>Trata de identificar cuando realmente necesitas un framework, porque no siempre hará falta, y a veces la intención inicial de hacer el proyecto más rápido puede resultar en horas buscando documentación de funciones que no conoces por el simple hecho de utilizar el framework en vez de PHP simplemente.</p>
<h2>Conclusiones</h2>
<p>Como habrás podido ver elegir un framework no es algo fácil, sobre todo si el proyecto va a llevar mucho tiempo. Cosas como la documentación o el soporte de ciertas funciones de manera nativa pueden resultar en horas ahorradas de implementación, así que piénsalo bien y trata de echarle un vistazo a varios antes de elegir uno.</p>
<p>Aquí dejo una serie de enlaces para entender más en profundidad los diferentes frameworks y ciertos términos que hemos visto como MVC u ORM.</p>
<ul>
<li><a href="http://framework.zend.com/">Página Oficial de Zend</a></li>
<li><a href="http://codeigniter.com/">Página Oficial de CodeIgniter</a></li>
<li><a href="http://cakephp.org/">Página Oficial de CakePHP</a></li>
<li><a href="http://www.symfony-project.org/">Página Oficial de Symfony</a></li>
<li><a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC en la wikipedia</a></li>
<li><a href="http://en.wikipedia.org/wiki/Object-relational_mapping">ORM en la wikipedia</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/que-framework-de-php-deberia-elegir/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Hacer un sistema de puntuación con PHP y jQuery</title>
		<link>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/</link>
		<comments>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 22:12:33 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1494</guid>
		<description><![CDATA[Introducción En muchas páginas se utilizan sistemas de puntuación. Normalmente suelen ser de 5 estrellas, en los que la gente vota que le ha parecido del 1 al 5. Desde el punto de vista de los desarrolladores plantéa muchas cuestiones interesantes, algunas más complejas que otras. En cualquier caso no es demasiado difícil, por lo [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>En muchas páginas se utilizan sistemas de puntuación. Normalmente suelen ser de 5 estrellas, en los que la gente vota que le ha parecido del 1 al 5. Desde el punto de vista de los desarrolladores plantéa muchas cuestiones interesantes, algunas más complejas que otras. En cualquier caso no es demasiado difícil, por lo que podemos cubrirlo en un solo tutorial.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/final.png" alt="Resultado Final del sistema de puntuación" title="Resultado Final del sistema de puntuación"/>
</div>
<p>Aquí vamos a diseñar, implementar y sobre todo explicar como hacer un <strong>sistema de puntuación de 5 estrellas con decimales intermedios</strong>, por lo que la gente puede votar cosas como 4.5 o 1.5. Además <strong>un mismo usuario no podrá votar más de una vez</strong>, por lo que intentaremos hacer este sistema de votación lo más acorde con los gustos reales de la media de los usuarios.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/puntuacion.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/puntuacion/index.html" class="demo"></a>
</div>
<h2><span>Paso 1. </span>Diseño</h2>
<p>Antes que nada tenemos que hacer el maquetado del sistema de puntuación. Tenemos que pensar en términos de medias estrellas, porque vamos a admitir la votación de 4.5, por ejemplo, como hemos comentado en la introducción. Esto plantéa la primera dificultad, porque ¿cómo hacemos para unirlas todas? o ¿cómo sabemos que el usuario está seleccionando una u otra parte de la estrella? Podrías pensar en utilizar 5 imágenes, de tres tipos, estrellas vacías, medias estrellas y estrellas enteras. Pero entonces no podrías diferenciar fácilmente si un usuario está en la parte izquierda o en la derecha. Así que es un poco más complicado que eso.</p>
<p>En realidad gran parte de la solución vendrá con jQuery, pero de momento hay un hecho a remarcar. Tenemos que usar sprites. Sprite es una imagen compuesta de varias, que se envía una vez, y con CSS se selecciona la imagen dentro del archivo que queremos mostrar. Normalmente se usa para hacer más rápida la carga de la página, porque el navegador y el servidor sólo se tienen que conectar una vez para pasar todas las imágenes en un solo archivo. Pero en nuestro caso no es esa cuestión la más importante, lo importante es que <strong>si no tuviéramos sprites, cuando cambiáramos parte de una estrella tendríamos que enviar el archivo, después de finalizar la carga de la página.</strong> Esto supone una carga innecesaria en el ancho de banda fuera de tiempo.</p>
<p>Echemos un vistazo al código HTML, será algo bastante simple, basándonos en nuestra implementación concreta y dado que solo queremos 5 estrellas.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1&quot;</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;puntuacion&quot;</span>&gt;</span>		
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;0.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#0.5&quot;</span>&gt;</span>0.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#1&quot;</span>&gt;</span>1<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#1.5&quot;</span>&gt;</span>1.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;2/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#2&quot;</span>&gt;</span>2<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;2.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#2.5&quot;</span>&gt;</span>2.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;3/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#3&quot;</span>&gt;</span>3<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;3.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#3.5&quot;</span>&gt;</span>3.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;4/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#4&quot;</span>&gt;</span>4<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;4.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#4.5&quot;</span>&gt;</span>4.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#5&quot;</span>&gt;</span>5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span> <span style="color: #808080; font-style: italic;">&lt;!-- fin puntuacion #1 --&gt;</span>
&nbsp;
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;num_votos&quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>Votos: <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span> <span style="color: #808080; font-style: italic;">&lt;!-- fin #num_votos --&gt;</span></pre></td></tr></table></div>

<p>Cada línea dentro del div con id 1 representa media estrella, probablemente te parezca raro que no haya ningún tag <img>, pero no te preocupes, verás la razón en el código jQuery. Además, para codificar el CSS debemos pensar en cuantos &#8220;estados&#8221; van a tener nuestras estrellas. La respuesta es 3, uno para cuando esté vacía, otro para cuando esté establecida y otro para el estado <i>hover</i>, cuando un usuario esté poniendo el ratón por encima. Mira este gráfico para aclararte un poco:</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/esquema_tipos_estrellas.jpg" alt="Gráfico de los tres tipos de estrellas" title="Gráfico de los tres tipos de estrellas"/>
</div>
<p>Por tanto, en el CSS tendremos en cuenta esto. Y ya que estamos, recordaremos que tenemos sprites, por lo que el fondo, se va a realizar simplemente con CSS sobre la misma imagen. En concreto debemos tener un sprite para la parte derecha de las distintas estrellas y uno para la parte izquierda. Adicionalmente, añadimos un sprite para las estrellas enteras, pero esto es una mera formalidad y en realidad no se usará. Nuestro CSS quedará así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.puntuacion</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">pointer</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin-right</span><span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">clear</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">both</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span> <span style="color: #000000; font-weight: bold;">right</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">visible</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>  
&nbsp;
<span style="color: #6666ff;">.puntuacion</span><span style="color: #3333ff;">:after </span><span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">content</span><span style="color: #00AA00;">:</span> <span style="color: #ff0000;">'.'</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">clear</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">both</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">visibility</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>    
&nbsp;
<span style="color: #6666ff;">.estrella</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span> <span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;">35px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;">35px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> inline-<span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">text-indent</span><span style="color: #00AA00;">:</span> <span style="color: #933;">-999em</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">pointer</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin-top</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1em</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>         
&nbsp;
<span style="color: #6666ff;">.estrella_izq</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_der</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;">18px</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella</span> a <span style="color: #00AA00;">&#123;</span> 
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella_izq</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_izq</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite_izq.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella_der</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_der</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite_der.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span> <span style="color: #808080; font-style: italic;">/* Estrella Vacía */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
div<span style="color: #6666ff;">.puntuacion</span> div<span style="color: #6666ff;">.on</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">-45px</span><span style="color: #00AA00;">;</span> <span style="color: #808080; font-style: italic;">/* Estrella Establecida */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
div<span style="color: #6666ff;">.puntuacion</span> div<span style="color: #6666ff;">.hover</span> a<span style="color: #00AA00;">,</span>
div<span style="color: #6666ff;">.puntuacion</span> div a<span style="color: #3333ff;">:hover </span><span style="color: #00AA00;">&#123;</span>      
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">-90px</span><span style="color: #00AA00;">;</span>  <span style="color: #808080; font-style: italic;">/* Estrella Hover */</span>
<span style="color: #00AA00;">&#125;</span></pre></td></tr></table></div>

<p>Los detalles de como maquetarlo para que quede lo mejor posible no son demasiado importantes, quizá destacar que nos movemos por el sprite para seleccionar los diferentes tipos de estrellas. Además cuando establezcas un elemento con una imagen como <i>background</i>, debes tener en cuenta que si el elemento no tiene ancho definido, debes hacerlo para que el fondo se vea correctamente.</p>
<h2><span>Paso 2. </span>Plugin en jQuery</h2>
<p>Para realizar toda la funcionalidad que necesitamos podremos simplemente codificarlo en jQuery, pero de cara a una posible mejora en el futuro, meteremos todo el código en un plugin hecho por nosotros. Así que veamos en primer lugar como se crea un plugin muy rápidamente: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Declaración del plugin</span>
jQuery.<span style="color: #660066;">fn</span>.<span style="color: #660066;">plugin_tonto</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>param1<span style="color: #339933;">,</span> param2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Soy un plugin y estoy funcionando'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Llamada al plugin</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#elemento'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">plugin_tonto</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'valor1'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'valor2'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Como puedes ver es muy simple, es importante resaltar, como probablemente ya supongas, que en $(this) dentro del plugin tendremos el elemento que lo ha llamado, en este caso $(&#8216;#elemento&#8217;).</p>
<p>Así que ahora empezemos a codificar nuestro plugin de verdad. Debemos tener 1 parámetro, la url donde vamos a mandar los datos para que se procesen (será un script en PHP, que veremos luego). Además este plugin se va a encargar de mucha cosas, por lo que mejor vemos parte por parte desde arriba del código hasta el final.</p>
<h3>Funciones con Cookies y estableciendo variables</h3>
<p>Aquí vemos como establecemos una serie de variables necesarias para que el plugin funcione, como la url a dónde mandaremos la petición POST, o la serie de estrellas que tenemos en nuestro HTML. Además utilizamos dos funciones para manejar las cookies en javascript plano.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> createCookie<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #339933;">,</span>value<span style="color: #339933;">,</span>days<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>days<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> date <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		date.<span style="color: #660066;">setTime</span><span style="color: #009900;">&#40;</span>date.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>days<span style="color: #339933;">*</span><span style="color: #CC0000;">24</span><span style="color: #339933;">*</span><span style="color: #CC0000;">60</span><span style="color: #339933;">*</span><span style="color: #CC0000;">60</span><span style="color: #339933;">*</span><span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> expires <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;; expires=&quot;</span><span style="color: #339933;">+</span>date.<span style="color: #660066;">toGMTString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #003366; font-weight: bold;">var</span> expires <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
	document.<span style="color: #660066;">cookie</span> <span style="color: #339933;">=</span> <span style="color: #000066;">name</span><span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #339933;">+</span>value<span style="color: #339933;">+</span>expires<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;; path=/&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> readCookie<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> nameEQ <span style="color: #339933;">=</span> <span style="color: #000066;">name</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #003366; font-weight: bold;">var</span> ca <span style="color: #339933;">=</span> document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">split</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">';'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>i <span style="color: #339933;">&lt;</span> ca.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> c <span style="color: #339933;">=</span> ca<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #660066;">charAt</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span><span style="color: #3366CC;">' '</span><span style="color: #009900;">&#41;</span> c <span style="color: #339933;">=</span> c.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>c.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span>nameEQ<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span> c.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span>nameEQ.<span style="color: #660066;">length</span><span style="color: #339933;">,</span>c.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Este par de funciones se sale del objetivo del tutorial, pero básicamente sirven para establecer y guardar cookies, usando javascript. Si quieres más información la tienes por <a href="http://www.quirksmode.org/js/cookies.html">aquí</a>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>url <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> container <span style="color: #339933;">=</span> jQuery<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
jQuery.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>container<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
	puntos<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	url<span style="color: #339933;">:</span> url
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> estrellas <span style="color: #339933;">=</span> jQuery<span style="color: #009900;">&#40;</span>container<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.estrella'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Línea 6</strong>. Establecemos los atributos puntos y url, como si pertenecieran a container. De tal forma que cuando queramos acceder a ellos simplemente haremos container.url o container.puntos</p>
<p><strong>Línea 9</strong>. Seleccionamos todas las estrellas (en realidad serán media estrellas) y tendremos un total de 10 elementos en la variable <i>estrellas</i>.</p>
<h3>Definiendo eventos sobre las estrellas</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">estrellas
		.<span style="color: #660066;">mouseover</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">llenar</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #660066;">mouseout</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #000066;">focus</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">llenar</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #000066;">blur</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Cuando se hace click en una estrella</span>
estrellas.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
   	<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>readCookie<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'votado'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>estrellas.<span style="color: #660066;">index</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> .5<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> .5<span style="color: #339933;">;</span>
&nbsp;
      	$.<span style="color: #660066;">post</span><span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">url</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
      		<span style="color: #3366CC;">&quot;id&quot;</span><span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">parent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'id'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
        	<span style="color: #3366CC;">&quot;puntos&quot;</span><span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">href</span>.<span style="color: #660066;">split</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span> 
      	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      	createCookie<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;votado&quot;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">365</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      	eventos.<span style="color: #660066;">establecer_de_BD</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
	<span style="color: #009900;">&#125;</span>   
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>En la primera parte del código establecemos las acciones a realizar cuando pase una de esos eventos predefinidos en jQuery. Todas las llamadas que son <i>eventos.algo</i> pertenecen a un array que definiremos después.</p>
<p> Además definimos el evento click sobre cualquiera de las estrellas. Esto generará que se calcule la puntuación seleccionada y se envía a través del método POST a la url pasada al plugin. Antes de hacer nada para no molestar al servidor si realmente el usuario no puede votar porque ya lo ha hecho, miramos si tiene la cookie que pusimos en una ejecución anterior.</p>
<p>Si realmente es su primera vez votando, se manda la actualización, se establece una cookie para que no vote de nuevo y cuando se ha finalizado el envío se hace una consulta a la BD para actualizar la nueva puntuación. Esto resulta un poco ineficiente pero no quería perder el lado docente del tutorial, y creo que es más claro. En cualquier caso debes tener en mente que se podría devolver la nueva puntuación directamente desde la primera petición POST. </p>
<h3>Algunas funciones útiles e inicio de la puntuación</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> eventos <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #006600; font-style: italic;">// llenar hasta la posición del ratón.</span>
	llenar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>el<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 		
		<span style="color: #003366; font-weight: bold;">var</span> index <span style="color: #339933;">=</span> estrellas.<span style="color: #660066;">index</span><span style="color: #009900;">&#40;</span>el<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
		estrellas
			.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'width'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'100%'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
			.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>index<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// quitar todas las estrellas.</span>
	quitar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 		
		estrellas
			.<span style="color: #660066;">filter</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
			.<span style="color: #660066;">filter</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// reiniciar el sistema.</span>
	reiniciar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 	
		<span style="color: #003366; font-weight: bold;">var</span> unidad <span style="color: #339933;">=</span> parseInt<span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">puntos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> decimales <span style="color: #339933;">=</span> container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">-</span> unidad<span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> num_estrellas <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>unidad <span style="color: #339933;">*</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>decimales <span style="color: #339933;">&gt;=</span> .5<span style="color: #009900;">&#41;</span>
			num_estrellas <span style="color: #339933;">+=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
&nbsp;
		estrellas.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> num_estrellas<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	establecer_de_BD<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">//Establecemos la puntuación desde la BD</span>
		$.<span style="color: #660066;">post</span><span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">url</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;peticion&quot;</span><span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;id&quot;</span><span style="color: #339933;">:</span> estrellas.<span style="color: #660066;">parent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'id'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
		   <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		     $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#num_votos p'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Votos: &quot;</span> <span style="color: #339933;">+</span> data.<span style="color: #660066;">votos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 		     
		     container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">=</span> data.<span style="color: #660066;">puntuacion</span><span style="color: #339933;">;</span>  
		     eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
		   <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>    
&nbsp;
<span style="color: #006600; font-style: italic;">//Al principio establecemos el sistema con el valor que corresponde</span>
eventos.<span style="color: #660066;">establecer_de_BD</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Línea 3</strong>. Ahora creamos un array del que antes hemos hablado, llamado eventos, es un array asociativo compuesto por funciones. En esta línea definimos la primera función, que se encarga de ir componiendo las estrellas con la clase hover, para dar el efecto de llenado progresivo según se mueve el ratón.</p>
<p><strong>Línea 11</strong>. Esta función se encarga de quitar el efecto hover cuando dejamos de poner el ratón encima de las estrellas.</p>
<p><strong>Línea 18</strong>. Reiniciar es una funcíón para establecer el número de medias estrellas vacías que tenemos, para ello se &#8220;parte&#8221; el número entre la unidad y los decimales, y se opera con ellos. Los detalles los puedo explicar en los comentarios, pero es relativamente sencillo, teniendo en cuenta que tenemos siempre el doble de elementos por ser medias estrellas. Así que he establecido que si se tiene de X a X.5 se marca la mitad de una estrella, y si se tiene de X.5 a X+1 se tiene otra nueva estrella completa.</p>
<p><strong>Línea 29</strong>. Para que el sistema de puntuación funcione necesitamos ver el número de votos y la puntuación de la base de datos y establecerla con la funcion reiniciar. Así que se hace una petición POST y con el resultado en json se establece el resultado.</p>
<p>En la parte final del plugin ejecutamos por primera vez <i>establecer_de_BD</i> para poner el número de estrellas cuando se carga la página así como el número de votos.</p>
<h2><span>Paso 3. </span>Parte servidor con PHP y MySQL</h2>
<p>Hasta ahora tenemos una serie de estrellas que al hacer click en ellas nos mandan los datos actualizados y cuando se cargan nos lo piden. Pero de momento no tenemos un script que se encargue de recibir esas peticiones y actuar en consecuencia.</p>
<p>Es por ello que necesitamos pensar en dos cosas, qué vamos a hacer y cómo vamos a guardar los datos de las puntuaciones. Contestemos primero al problema de almacenar las puntuaciones.</p>
<h3>MySQL es la solución</h3>
<p>Contradiciendo a la navaja de Ockham, en este caso la solución más compleja es la mejor. Y es que podríamos planternos la posibilidad de guardar los votos en un archivo de texto, por ejemplo, pero esto resultaría en problemas de concurrencia, que MySQL resuelve por sí mismo, sin ni siquiera tener que saber como desarrollador que algo llamado concurrencia existe (uno de los temas más complejos en programación, por cierto).</p>
<p>Así que creemos una tabla realmente simple donde meteremos nuestros datos: </p>
<div class="image">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/Tabla_BD_Puntuaciones.png" alt="Tabla BD Puntuaciones" title="Tabla BD Puntuaciones"/>
</div>
<p>Para crearla haríamos lo siguiente con un IDE de bases de datos o desde un terminal:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">CREATE</span> <span style="color: #990099; font-weight: bold;">TABLE</span> puntuaciones
<span style="color: #FF00FF;">&#40;</span>
id <span style="color: #999900; font-weight: bold;">INT</span><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">11</span><span style="color: #FF00FF;">&#41;</span> <span style="color: #CC0099; font-weight: bold;">NOT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span> <span style="color: #FF9900; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #000033;">,</span>
puntos <span style="color: #999900; font-weight: bold;">DOUBLE PRECISION</span> <span style="color: #CC0099; font-weight: bold;">NOT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span><span style="color: #000033;">,</span>
votos <span style="color: #999900; font-weight: bold;">INT</span><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">11</span><span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">DEFAULT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span><span style="color: #000033;">,</span>
<span style="color: #990099; font-weight: bold;">PRIMARY KEY</span> <span style="color: #FF00FF;">&#40;</span>id<span style="color: #FF00FF;">&#41;</span>
<span style="color: #FF00FF;">&#41;</span> CHARACTER <span style="color: #990099; font-weight: bold;">SET</span><span style="color: #CC0099;">=</span>utf8<span style="color: #000033;">;</span></pre></td></tr></table></div>

<h3>Completando el sistema con PHP</h3>
<p>Por último necesitamos un archivo de configuración para simplificar la defición de constantes, una clase para facilitar el acceso a la BD y un script (<i>post.php</i>) para recibir y atender las peticiones.</p>
<p>Nuestro esquema de comunicación se puede resumir en algo así, siendo el plugin de jQuery el encargado de comunicarse con el servidor y de lidiar con las votaciones repetidas.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/esquema_puntuacion.png" alt="Esquema conexión de nuestro sistema de puntuación" title="Esquema conexión de nuestro sistema de puntuación"/>
</div>
<p>Así que vamos con el primer archivo PHP.Este archivo de configuración será simplemente: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009933; font-style: italic;">/** El nombre de tu base de datos */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_NAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'nombre_base_de_datos'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Tu nombre de usuario de MySQL */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_USERNAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'usuario'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Tu contraseña de MySQL */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_PASSWORD'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'pass'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_HOSTNAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'hostname'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Codificación de caracteres para la base de datos. */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_CHARSET'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'utf8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>La clase, llamada <i>puntos.class.php</i> será bastante sencilla también: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">'config.inc.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Puntos <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$db</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$id</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span>DB_HOSTNAME<span style="color: #339933;">,</span> DB_USERNAME<span style="color: #339933;">,</span> DB_PASSWORD<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		<span style="color: #990000;">mysql_set_charset</span><span style="color: #009900;">&#40;</span>DB_CHARSET<span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
		<span style="color: #990000;">mysql_select_db</span><span style="color: #009900;">&#40;</span>DB_NAME<span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
&nbsp;
		<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;INSERT IGNORE INTO puntuaciones (id, votos, puntos) &quot;</span>
		 		<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;VALUES (<span style="color: #006699; font-weight: bold;">$this-&gt;id</span>,0,0)&quot;</span><span style="color: #339933;">;</span> 
&nbsp;
		<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Incluimos el archivo de configuración y en el constructor hacemos tres cosas:</p>
<ol>
<li>Establecemos la conexión con la base de datos.</li>
<li>Establecemos como atributo privado de la clase el id del sistema de puntuación que nos pasan.</li>
<li>Insertamos una nueva fila con votos y puntuación a 0 si no existía ya.</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">function</span> getPuntuacion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>						
		<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT puntos as puntuacion, votos &quot;</span>
				<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;FROM puntuaciones &quot;</span>
				<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;WHERE id = <span style="color: #006699; font-weight: bold;">$this-&gt;id</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$resultado</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">mysql_fetch_assoc</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultado</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Aquí recogemos en un array asociativo la consulta de el número de votos y los puntos que tiene un determinado sistema. Otra vez, lo sabremos por el id que nos pasaron en el constructor y que ya tenemos guardado como atributo.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">function</span> setPuntuacion<span style="color: #009900;">&#40;</span><span style="color: #000088;">$puntos</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_COOKIE</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'votado'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>     
			<span style="color: #000088;">$puntos</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$puntos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;UPDATE puntuaciones &quot;</span><span style="color: #339933;">.</span>
					 <span style="color: #0000ff;">&quot;SET puntos = ((puntos * votos) + <span style="color: #006699; font-weight: bold;">$puntos</span>) / (votos + 1), &quot;</span><span style="color: #339933;">.</span>
					 <span style="color: #0000ff;">&quot;votos = votos + 1 &quot;</span><span style="color: #339933;">.</span> 
					 <span style="color: #0000ff;">&quot;WHERE id = <span style="color: #006699; font-weight: bold;">$this-&gt;id</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
			 <span style="color: #b1b100;">return</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">//Fin de la clase</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Este último método mira si se tiene una cookie previamente establecida y si no es así actualiza la base de datos con los puntos pasados como parámetro, aumentando también el número de votos a uno más de los que había. La comprobación de la cookie no es estrictamente necesaria, porque previamente el plugin se ha encargado de ver eso, pero no está de más y no supone casi carga al servidor.</p>
<p>El sistema de establecer una cookie cuando un usuario vote para que no lo haga más no es una solución perfecta, porque se puede saltar fácilmente, pero es una primera aproximación y quizá en un futuro enseñe como mejorar esto. En cualquier caso se puede ver un uso práctico de las cookies con PHP y una aplicación real.</p>
<h4>Script que recibe las peticiones</h4>
<p>Por último tenemos nuestro archivo <i>post.php</i> en el que recibimos las peticiones:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Incluimos la clase puntos</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">'puntos.class.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #000088;">$pt</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Puntos<span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'peticion'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'peticion'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">echo</span> <span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$pt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getPuntuacion</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'puntos'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$pt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPuntuacion</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'puntos'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>  
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p><strong>Línea 8. </strong>Nos han hecho una petición para saber el número de votos y la puntuación. Así que llamamos al método definido antes que se encarga de manejar esa petición.</p>
<p><strong>Línea 11. </strong>Establecemos la nueva puntuación y aumentamos el número de votos en 1. Nuestro método ya se encarga de comprobar la cookie y de limpiar la entrada de datos, usando <i>mysql_real_escape_string</i>, como hemos comentado antes.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/puntuacion.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/puntuacion/index.html" class="demo"></a>
</div>
<h2>Conclusiones</h2>
<p>Si bien es cierto que hay cosas que pulir, como por ejemplo en términos de accesibilidad si no se tiene javascript activado, o de seguridad, para evitar que un usuario pueda saltarse el control que hemos hecho con la cookie, este tutorial cubre muchos puntos, que espero, te hayan sido útiles.</p>
<p>El plugin está basado en uno mucho más complejo y grande que ya va por su versión 3.13. Lo puedes encontrar <a href="http://www.fyneworks.com/jquery/star-rating/">aquí</a>.</p>
<p>Las estrellas usadas (aunque estaban enteras) son de <a href="http://www.customicondesign.com"> Customicon Design</a>.</p>
<p>Si tienes cualquier duda, no dudes en preguntar en la sección de comentarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hacer una fila de una tabla clickable en HTML</title>
		<link>http://www.polargeek.net/hacer-una-fila-de-una-tabla-clickable-en-html/</link>
		<comments>http://www.polargeek.net/hacer-una-fila-de-una-tabla-clickable-en-html/#comments</comments>
		<pubDate>Wed, 12 May 2010 23:27:49 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tabla]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1360</guid>
		<description><![CDATA[Filas en HTML y enlaces Este es el típico problema que hasta que no te pasa, ni siquiera sabías que existía. La cuestión es la siguiente: 1 2 3 4 5 6 7 &#60;table border=&#34;0&#34; width=&#34;&#34;&#62; &#60;tr&#62; &#60;td&#62;Uno&#60;/td&#62; &#60;td&#62;Dos&#60;/td&#62; &#60;td&#62;Tres&#60;/td&#62; &#60;/tr&#62; &#60;/table&#62; Teniendo una tabla en HTML como la de arriba queremos que una fila [...]]]></description>
			<content:encoded><![CDATA[<h2>Filas en HTML y enlaces</h2>
<p><img src="http://static.polargeek.net/uploads/san_diego.jpg" alt="San Diego (USA)" border="0" /></p>
<p>Este es el típico problema que hasta que no te pasa, ni siquiera sabías que existía. La cuestión es la siguiente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">table</span> <span style="color: #000066;">border</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;0&quot;</span> <span style="color: #000066;">width</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;&quot;</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">tr</span>&gt;</span>
         <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">td</span>&gt;</span>Uno<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">td</span>&gt;</span>
         <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">td</span>&gt;</span>Dos<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">td</span>&gt;</span>
         <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">td</span>&gt;</span>Tres<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">td</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">tr</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">table</span>&gt;</span></pre></td></tr></table></div>

<p>Teniendo una tabla en HTML como la de arriba queremos que una fila entera se comporte como un enlace hacia otra página, es decir, como si estuviera entre la etiqueta anchor de HTML (<a href="#"></a>).</p>
<h2>Lo más intuitivo pero incorrecto</h2>
<p>Pues metes el elemento &#8216;table row&#8217; (tr) entre la etiqueta anchor y listo.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>table border<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;0&quot;</span> width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;link.html&quot;</span><span style="color: #339933;">&gt;</span>			
<span style="color: #339933;">&lt;</span>tr<span style="color: #339933;">&gt;</span>
     <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;</span>Uno<span style="color: #339933;">&lt;/</span>td<span style="color: #339933;">&gt;</span>
     <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;</span>Dos<span style="color: #339933;">&lt;/</span>td<span style="color: #339933;">&gt;</span>
     <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;</span>Tres<span style="color: #339933;">&lt;/</span>td<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>tr<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>table<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Por desgracia esto no funciona, así que mal asunto. A partir de este punto es cuestión de echarle mucha imaginación o de intentar pensar un poco, en ambos casos no llegaremos a la solución perfecta, pero cerca nos quedaremos.</p>
<h2>Imaginación al poder</h2>
<p>Una solución es crear un anchor que se vaya moviendo por encima de cada fila según el mouse vaya pasando por ellas. Como puedes suponer, esta solución está en JavaScript, concretamente se ha usado jQuery y se ha realizado un plugin. Su uso es tan sencillo como:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'table#mitabla tr'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">superLink</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a:last'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Pros</h3>
<p>Pues probablemente que es una solución con mucha imaginación detrás y su uso es realmente sencillo. Puedes ver el demo <a rel="external nofollow" href="http://james.padolsey.com/demos/plugins/jQuery/superLink/">aquí</a>, donde también hay un enlace donde el autor explica su idea.</p>
<h3>Contras</h3>
<p>Pues que al usar CSS y definir :hover (para cuando se pase el ratón por encima) no funciona. Es decir que el comportamiento normal que tiene un anchor en una página con respecto al CSS no existe. Además de eso, lo cierto es que tiene demasiada complejidad para una cosa que en principio puede parecer tan simple.</p>
<h2>Solución intuitiva</h2>
<p>Esta segunda opción viene dada por <a rel="external nofollow" href="http://radio.javaranch.com/pascarello/2005/05/19/1116509823591.html">Eric</a>. Lo cierto es que es bastante más sencilla, tiene en cuenta que realmente lo que queremos es que al hacer click en cualquier punto de una fila nos lleve a otra página. Así que con algo tan sencillo como esto no tendríamos que complicarnos más la vida:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">window.<span style="color: #000066;">onload</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    ConvertRowsToLinks<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;table1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> ConvertRowsToLinks<span style="color: #009900;">&#40;</span>xTableId<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">//Seleccionamos todas las table row (filas) del documento</span>
    <span style="color: #003366; font-weight: bold;">var</span> rows <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>xTableId<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;tr&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">//Las recorremos con un for</span>
    <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>i<span style="color: #339933;">&lt;</span>rows.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//Buscamos dentro de cada table row (tr) un elemento a</span>
        <span style="color: #003366; font-weight: bold;">var</span> link <span style="color: #339933;">=</span> rows<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>link.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">//Si lo encontramos asociamos el evento click con la redirección</span>
            rows<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #003366; font-weight: bold;">Function</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;document.location.href='&quot;</span> <span style="color: #339933;">+</span> link<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">href</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Pros</h3>
<p>Su simplicidad en cuanto a codificación, y que si respeta el problema del CSS. He preparado un ejemplo sencillo con Google Code PlayGround (del que hice <a href="http://www.polargeek.net/ejecutar-codigo-javascript-online-con-google/">un post</a> hace un tiempo). El ejemplo está <a href="http://savedbythegoog.appspot.com/?id=daf334169986a3bdfee67f9a3114f2402684372a">aquí</a> (el enlace lo he puesto con #1 y #2 para no salir de la página al hacer click pero puedes ver que funciona en la barra de direcciones <img src='http://www.polargeek.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). Además esto está en JavaScript plano, por lo que no necesitamos incluir jQuery, como pasaba con el anterior.</p>
<h3>Contras</h3>
<p>Cuando el usuario no ejecuta el click sino intenta ir a la página de otra forma (por ejemplo pinchando con la rueda para abrir en otra pestaña) pues no lo podemos detectar. Hay varios eventos asociados a un anchor que nos pueden ser útiles (middle-click para el caso de la rueda, por decir alguno), pero tendríamos que definir la función asociado a cada evento y eso no es muy cómodo que digamos.</p>
<h2>Conclusión</h2>
<p>Hay tantas soluciones como se te puedan ocurrir, de hecho hay más plugins de jQuery por ahí con la misma función que el mostrado en el ejemplo primero, pero estas dos soluciones me parecieron las más destacables. ¿Tienes alguna otra?</p>
<p>Foto de <a href="http://www.flickr.com/photos/wouterpostma/1069260173/">Wouter</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/hacer-una-fila-de-una-tabla-clickable-en-html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
