Mostrando entradas con la etiqueta javascript. Mostrar todas las entradas
Mostrando entradas con la etiqueta javascript. Mostrar todas las entradas

jueves, 17 de septiembre de 2015

jQuery explode effect - Efecto explosión


El método explode os permitirá dar un efecto explosión a elementos div.

El método explode poseé dos argumentos options y callback:

El argumento options tiene las siguientes opciones: pieces, columns, pixels y speed.

pieces: para indicar el número de piezas que conformarán la explosión.
columns: para indicar el número de columnas.
pixels: para indicar los píxeles de expansión de la explosión.
speed: para indicar la velocidad de la explosión.

Por defectos el argumento options viene configurado de la siguiente manera:


 var defaults = {
  pieces: 20,
  columns: 4,
  pixels: 50,
  speed: 500
 };

El argumento callback te permitirá incluir instrucciones una vez ha finalizado la animación.

A continuación puedes ver una serie de ejemplos, haz click sobre los elementos:



jQuery explode effect - Efecto explosión by jQuery Manual





Código fuente con el plugin y los ejemplos ...
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>

<script>

(function($){
/* Author: Manu Dávila | Web: http://jquery-manual.blogspot.com */
$.fn.explode = function(options, callback){
 var defaults = {
  pieces: 20,
  columns: 4,
  pixels: 50,
  speed: 500
 };
 
 if (options === undefined){options = defaults;}
 if (callback === undefined){callback = function(){}};
 if (options.pieces === undefined){options.pieces = defaults.pieces;}
 if (options.columns === undefined){options.columns = defaults.columns;}
 if (options.pixels === undefined){options.pixels = defaults.pixels;}
 if (options.speed === undefined){options.speed = defaults.speed;}
 
 var background_color_piece = this.css("backgroundColor");
 var background_image_piece = this.css("backgroundImage");
 var border_radius_piece = this.css("borderRadius");
 
 this.append("<table style='width: 100%; height: "+this.height()+"px;'></table>");
 for (x = 0; x < (options.pieces/options.columns); x++)
 {
  content = '';
 
  var block = "style='background-color: "+background_color_piece+"; background-image: "+background_image_piece+"; padding: 5px; background-size: 100% 100%; background-repeat: no-repeat; border-radius: "+border_radius_piece+";'";
  
  for (y = 0; y < options.columns; y++)
  {
   content = content + "<td "+block+"></td>";
  }
 
  this.find("table").append("<tr>"+content+"</tr>");
 }
 
 this.css("background", "transparent");
 this.find("table").css({position: "relative"});
 this.find("table").animate({width: "+="+options.pixels, height: "+="+options.pixels, opacity: "-=1", left: "-="+(options.pixels/2), top: "-="+(options.pixels/2)}, options.speed, function(){callback(); $(this).remove();}); 
};
})(jQuery);

 $(function(){
 $("#box-1").on("click", function(){
   $(this).explode({columns: 8, pieces: 64, pixels: 100}, 
   function(){
   $("#box-1").css({backgroundColor: "orange"}); 
   });
 });
 
 $("#img-1").on("click", function(){
   $(this).explode({columns: 4, pieces: 16, pixels: 300, speed: 800}, 
   function(){ 
   $("#img-1").css({backgroundImage: "url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEsomZLE4xMMymwuehFoP1YS9-lZwWcdySyJ9cDSXWBAybrBhEAJoDf8RKMn8MvSPfyfp5eGEVkgBzvKv7o2dn7_iru_BtFgossaTVa8yNU0UpjM2s9-MIFhI0aMr-MI6u7Dzyf8PROKs/s1600/jquery.png)",  backgroundSize: "100% 100%"}); 
   });
 });
 
 $("#img-2").on("click", function(){
   $(this).explode({columns: 10, pieces: 108, pixels: 500, speed: 800}, 
   function(){ 
   $("#img-2").css({backgroundImage: "url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibogdTxELh9pPum7wBneX99F-q1ZDU-XA218Gx3EDpz0wDlcREqB-UiRNwhF56fLaEuE7_9YMBAtlhttj2C4IpH5za0l_HSaYULnq0I9sYcafBvxxaSl-l1P1mWpPRQRm2Npi1Fglvyog/s1600/color.jpeg)", backgroundSize: "100% 100%"}); 
   });
 });
 });
</script>

<style>
#box-1{
width: 150px; 
height: 150px; 
border-radius: 4px;
background-color: orange;
border-radius: 50%;
}

#img-1{
width: 160px; 
height: 160px; 
background-image: url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEsomZLE4xMMymwuehFoP1YS9-lZwWcdySyJ9cDSXWBAybrBhEAJoDf8RKMn8MvSPfyfp5eGEVkgBzvKv7o2dn7_iru_BtFgossaTVa8yNU0UpjM2s9-MIFhI0aMr-MI6u7Dzyf8PROKs/s1600/jquery.png);
background-size: 100% 100%;
border-radius: 50%;
}

#img-2{
width: 160px; 
height: 160px; 
background-image: url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibogdTxELh9pPum7wBneX99F-q1ZDU-XA218Gx3EDpz0wDlcREqB-UiRNwhF56fLaEuE7_9YMBAtlhttj2C4IpH5za0l_HSaYULnq0I9sYcafBvxxaSl-l1P1mWpPRQRm2Npi1Fglvyog/s1600/color.jpeg);
background-size: 100% 100%;
}


</style>

</head>
<body>
<div style="margin: 100px;">
<h2>jQuery explode effect - Efecto explosión by <a href="http://jquery-manual.blogspot.com">jQuery Manual</a></h2>
<div id="box-1"></div>
<hr />
<div id="img-1"></div>
<hr />
<div id="img-2"></div>
</div>
</body>
</html>


miércoles, 16 de septiembre de 2015

jQuery Spinbox - Crear un input number con jQuery y CSS3


Hola, en esta ocasión os traigo un método jQuery llamado spinbox que os servirá para emular el elemento input number de HTML5, el método spinbox puede ser muy útil para implementarlo en navegadores en los que el elemento input number no es compatible, de hecho, es peculiar que un navegador como Google Chrome en el S.O Android no acepta este elemento.

El método spinbox acepta las opciones fundamentales del input number como son: min, max, value y step. Cada una de ellas pueden ser configuradas al gusto.

Por defecto las opciones vienen con los siguientes valores:

 var defaults = {
  min: 0,
  max: 100,
  value: 0,
  step: 1
 };


Los icono de incremento y decremento son proporcionados por Font Awesome, estilizar el spinbox ya es cuestión de lo que necesitéis, CSS3 está en vuestras manos.

A continuación podéis ver unos ejemplos con un spinbox básico, un spinbox con números negativos y un spinbox con número en punto flotante y al final el código con el plugin y los ejemplos.



Spinbox by jQuery Manual

Por defecto

Números negativos: {min: -50, max: 50, value: -50}

Números en punto flotante: {min: 0, max: 10, value: 0, step: 0.1}



Código fuente del plugin con los ejemplos ...

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
<!-- Icons -->
<link rel="stylesheet" type="text/css" href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css" />

<script>

(function($){ 
/* Author: Manu Dávila | Web: http://jquery-manual.blogspot.com */
 $.fn.spinbox = function(options){
 var defaults = {
  min: 0,
  max: 100,
  value: 0,
  step: 1
 };
 if (options === undefined){options = defaults;}
 if (options.min === undefined) {options.min = defaults.min;}
 if (options.max === undefined) {options.max = defaults.max;}
 if (options.value === undefined) {options.value = defaults.value;}
 if (options.step === undefined) {options.step = defaults.step;}
 
 options.min = parseFloat(options.min);
 options.max = parseFloat(options.max);
 options.value = parseFloat(options.value);
 options.step = parseFloat(options.step);
 
 var input = this.find("input");
 var spin_up = this.find(".spin-up");
 var spin_down = this.find(".spin-down");
 
 input.val(options.value);
 
 spin_up.on("click", function(){
 
 if (Number(input.val()) !== NaN){
 
  if (parseFloat(input.val()) > options.max || parseFloat(input.val()) < options.min)
  {
   input.val(options.max);
   return;
  }
  
  if (parseFloat(input.val()) < options.max)
  {
  
   value = parseFloat(input.val())+options.step;
   if (String(value).match(/\./) && String(options.step).match(/\./))
   {
    max_decimal = String(options.step).split(".")[1];
    value = value.toFixed(max_decimal);
   }
   input.val(value);
  }
 }
 });
 
 spin_down.on("click", function(){
 if (Number(input.val()) !== NaN){
 
  if (parseFloat(input.val()) < options.min || parseFloat(input.val()) > options.max)
  {
   input.val(options.min);
   return;
  }
  
  if (parseFloat(input.val()) > options.min)
  {
   value = parseFloat(input.val())-options.step;
   if (String(value).match(/\./) && String(options.step).match(/\./))
   {
    max_decimal = String(options.step).split(".")[1];
    value = value.toFixed(max_decimal);
   }
   input.val(value);
  }
 }
 });
 
 
 };
})(jQuery);

 $(function(){
 $("#spinbox-1").spinbox();
 $("#spinbox-2").spinbox({min: -50, max: 50, value: -50});
 $("#spinbox-3").spinbox({min: 0, max: 10, value: 0, step: 0.1});
 });
</script>

<style>
.input-spinbox{
 border: 1px solid #D2E3EB;
 border-radius: 2px;
 padding-top: 5px;
 padding-bottom: 5px;
 padding-right: 2px;
 padding-left: 2px;
}

.input-spinbox:focus{
 border-color: 2px solid #2C426D;
}

.spin-up{
position: relative; 
left: -18px; 
top: -6px;
background-color: #5371AE;
color: #fff;
border-radius: 2px 2px;
}

.spin-down{
position: relative;
left: -36px;
top: 6px;
background-color: #5371AE;
color: #fff;
border-radius: 0px 0px 2px 2px;
}

.spin-up:hover, .spin-down:hover{
 cursor: pointer;
}

</style>

</head>
<body>
<h1>Spinbox by <a href="http://jquery-manual.blogspot.com">jQuery Manual</a></h1>
<h3>Por defecto</h3>
<div id="spinbox-1">
 <input type="text" name="spinbox-1" class="input-spinbox" />
 <span class="spin-up fa fa-angle-up fa-lg"></span>
 <span class="spin-down fa fa-angle-down fa-lg"></span>
</div>
<h3>Números negativos: {min: -50, max: 50, value: -50}</h3>
<div id="spinbox-2">
 <input type="text" name="spinbox-2" class="input-spinbox" />
 <span class="spin-up fa fa-angle-up fa-lg"></span>
 <span class="spin-down fa fa-angle-down fa-lg"></span>
</div>
<h3>Números en punto flotante: {min: 0, max: 10, value: 0, step: 0.1}</h3>
<div id="spinbox-3">
 <input type="text" name="spinbox-3" class="input-spinbox" />
 <span class="spin-up fa fa-angle-up fa-lg"></span>
 <span class="spin-down fa fa-angle-down fa-lg"></span>
</div>
</body>
</html>


martes, 15 de septiembre de 2015

Eliminar funciones en Javascript


Hola, en esta ocasión veremos un caso práctico de como eliminar funciones en javascript, para tal tarea crearemos una simple función que regresa un simple string, dos botones: uno para mostrar en un div el valor devuelto por la función y el otro para eliminar la función y mostrar un mensaje de que la función no existe. Para eliminar la función utilizaremos la propiedad undefined que nos permitirá en este caso indicar que a la función no le ha sido asignado ningún valor, por lo tanto, la función en ese instante dejará de existir en la memoria. Si intentamos acceder a ella a partir de ese instante obtendremos una excepción como la siguiente: Uncaught TypeError: foo is not a function. Por lo tanto es conveniente ir comprobando con una sentencia if de su existencia o no.



Eliminar funciones en Javascript




Código fuente del ejemplo ...

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script>
 /* Función a eliminar */
 foo = function(){
  return "Hello World";
 }
 
 window.onload = function(){
  /* Author: Manu Dávila | Web: http://jquery-manual.blogspot.com */
  /* Al hacer click sobre este botón la función estará operativa */
  document.getElementById("btn-1").onclick = function(){
   
   /* Si la función existe llamarla */
   if (foo !== undefined)
   {
    document.getElementById("result").innerHTML = foo();
   }
  };
  
  /* Al hacer click sobre este botón la función será destruida */
  document.getElementById("btn-2").onclick = function(){
  
   /* Destruir la función */
   foo = undefined;
   
   /* Si la función ha sido destruida */
   if (foo === undefined)
   {
    document.getElementById("result").innerHTML = "foo() no es una función";
   }
  };
 };
 
</script>
</head>
<body>
<h3>Eliminar funciones en Javascript</h3>
<button type="button" id="btn-1">Function foo()</button>
<button type="button" id="btn-2">Eliminar function foo()</button>
<div id="result"></div>
</body>
</html>


lunes, 14 de septiembre de 2015

jQuery Bounce - Efecto rebote con jQuery y CSS3 animations


En esta ocasion os traigo un método jQuery llamado bounce que te permitirá asignar un efecto bounce (rebote) a los elementos visibles del DOM html, para el efecto se utiliza CSS3 animations. por ejemplo, al hacer click o pasar el mouse sobre una imagen o tal vez un determinado div puedes mostrar un atractivo efecto rebote como podrás ver en los diferentes ejemplo que vienen a continuación.

Opciones por defecto del plugin:

 defaults = {
  pixels: 20,
  duration: 0.5,
  delay: 0,
  iteration_count: 1,
  direction: 'normal',
  timing_function: 'linear'
 };



Haz click en los círculos para ver el efecto Bounce

Default

{pixels: 40, duration: 1, direction: 'alternate', timing_function: 'ease-in-out'}

{duration: 0.7, timing_function: 'cubic-bezier(30,10,30,10)'}

Pasa el mouse sobre la siguiente imagen ...



Código fuente del plugin con los ejemplos ...

<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>

<script>
//Author: Manu Dávila | Web: http://jquery-manual.blogspot.com
(function($){
$.fn.bounce = function(options){
 defaults = {
  pixels: 20,
  duration: 0.5,
  delay: 0,
  iteration_count: 1,
  direction: 'normal',
  timing_function: 'linear'
 };
 
 if (options === undefined){options = defaults;}
 if (options.pixels === undefined) {options.pixels = defaults.pixels;}
 if (options.duration === undefined) {options.duration = defaults.duration;}
 if (options.delay === undefined) {options.delay = defaults.delay;}
 if (options.iteration_count === undefined) {options.iteration_count = defaults.iteration_count;}
 if (options.direction === undefined) {options.direction = defaults.direction;}
 if (options.timing_function === undefined) {options.timing_function = defaults.timing_function;}
 
 b_plus_width = new Array();
 b_plus_height = new Array();
 b_plus_width[0] = parseInt(this.width()+options.pixels);
 b_plus_height[0] = parseInt(this.height()+options.pixels);
 b_plus_width[1] = parseInt(this.width()+(options.pixels / 1.8));
 b_plus_height[1] = parseInt(this.height()+(options.pixels / 1.8));
 b_plus_width[2] = parseInt(this.width()+(options.pixels / 1.4));
 b_plus_height[2] = parseInt(this.height()+(options.pixels / 1.4));
 b_plus_width[3] = parseInt(this.width()+(options.pixels / 1.2));
 b_plus_height[3] = parseInt(this.height()+(options.pixels / 1.2));
 
 b_less_width = new Array();
 b_less_height = new Array();
 b_less_width[0] = parseInt(this.width()-options.pixels);
 b_less_height[0] = parseInt(this.height()-options.pixels);
 b_less_width[1] = parseInt(this.width()-(options.pixels / 1.2));
 b_less_height[1] = parseInt(this.height()-(options.pixels / 1.2));
 b_less_width[2] = parseInt(this.width()-(options.pixels / 1.4));
 b_less_height[2] = parseInt(this.height()-(options.pixels / 1.4));
 b_less_width[3] = parseInt(this.width()-(options.pixels / 1.8));
 b_less_height[3] = parseInt(this.height()-(options.pixels / 1.8));
 
 animation = "animation"+Math.floor((Math.random() * 1000000000000000) + 1);

 
 this.find(".style-bounce").remove();
 
 this.append("<style class='style-bounce'>@keyframes "+animation+" {12.5%{width: "+b_less_width[0]+"px; height: "+b_less_height[0]+"px;}25%{width: "+b_plus_width[0]+"px; height: "+b_plus_height[0]+"px;}37.5.%{width: "+b_less_width[1]+"px; height: "+b_less_height[1]+"px;}50%{width: "+b_plus_width[1]+"px; height: "+b_plus_height[1]+"px;}62.5%{width: "+b_less_width[2]+"px; height: "+b_less_height[2]+"px;}75%{width: "+b_plus_width[2]+"px; height: "+b_plus_height[2]+"px;}87.5%{width: "+b_less_width[3]+"px; height: "+b_less_height[3]+"px;}100%{width: "+b_plus_width[3]+"px; height: "+b_plus_height[3]+"px;}}</style>");
 this.css("animation-name", ""+animation+"");
 this.css("animation-duration", ""+options.duration+"s");
 this.css("animation-delay", ""+options.delay+"s");
 this.css("animation-iteration-count", ""+options.iteration_count+"");
 this.css("animation-direction", ""+options.direction+"");
 this.css("animation-timing-function", ""+options.timing_function+"");
 
 
 this.append("<style class='style-bounce'>@-webkit-keyframes "+animation+" {12.5%{width: "+b_less_width[0]+"px; height: "+b_less_height[0]+"px;}25%{width: "+b_plus_width[0]+"px; height: "+b_plus_height[0]+"px;}37.5.%{width: "+b_less_width[1]+"px; height: "+b_less_height[1]+"px;}50%{width: "+b_plus_width[1]+"px; height: "+b_plus_height[1]+"px;}62.5%{width: "+b_less_width[2]+"px; height: "+b_less_height[2]+"px;}75%{width: "+b_plus_width[2]+"px; height: "+b_plus_height[2]+"px;}87.5%{width: "+b_less_width[3]+"px; height: "+b_less_height[3]+"px;}100%{width: "+b_plus_width[3]+"px; height: "+b_plus_height[3]+"px;}}</style>");
 this.css("-webkit-animation-name", ""+animation+"");
 this.css("-webkit-animation-duration", ""+options.duration+"s");
 this.css("-webkit-animation-delay", ""+options.delay+"s");
 this.css("-webkit-animation-iteration-count", ""+options.iteration_count+"");
 this.css("-webkit-animation-direction", ""+options.direction+"");
 this.css("-webkit-animation-timing-function", ""+options.timing_function+"");
 
 this.append("<style class='style-bounce'>@-moz-keyframes "+animation+" {12.5%{width: "+b_less_width[0]+"px; height: "+b_less_height[0]+"px;}25%{width: "+b_plus_width[0]+"px; height: "+b_plus_height[0]+"px;}37.5.%{width: "+b_less_width[1]+"px; height: "+b_less_height[1]+"px;}50%{width: "+b_plus_width[1]+"px; height: "+b_plus_height[1]+"px;}62.5%{width: "+b_less_width[2]+"px; height: "+b_less_height[2]+"px;}75%{width: "+b_plus_width[2]+"px; height: "+b_plus_height[2]+"px;}87.5%{width: "+b_less_width[3]+"px; height: "+b_less_height[3]+"px;}100%{width: "+b_plus_width[3]+"px; height: "+b_plus_height[3]+"px;}}</style>");
 this.css("-moz-animation-name", ""+animation+"");
 this.css("-moz-animation-duration", ""+options.duration+"s");
 this.css("-moz-animation-delay", ""+options.delay+"s");
 this.css("-moz-animation-iteration-count", ""+options.iteration_count+"");
 this.css("-moz-animation-direction", ""+options.direction+"");
 this.css("-moz-animation-timing-function", ""+options.timing_function+"");
 
};
})(jQuery);

 $(function(){
  $("#box-1").on("click", function(e){
   $("#box-1").bounce();
  });
  
  $("#box-2").on("click", function(e){
   $("#box-2").bounce({pixels: 40, duration: 1, direction: 'alternate', timing_function: 'ease-in-out'});
  });
  
  $("#box-3").on("click", function(e){
   $("#box-3").bounce({duration: 0.7, timing_function: 'cubic-bezier(30,10,30,10)'});
  });
  
  $("#img").on("mouseover", function(e){
   $("#img").bounce({pixels: 10, duration: 1, timing_function: 'ease-in-out'});
  });
 });
</script>

<style>
 #box-1{
  background-color: orange;
  width: 50px;
  height: 50px;
  border-radius: 50%;
 }
 
 #box-2{
  background-color: green;
  width: 50px;
  height: 50px;
  border-radius: 50%;
 }
 
 #box-3{
  background-color: pink;
  width: 50px;
  height: 50px;
  border-radius: 50%;
 }
</style>


</head>
<body>
<h1>jQuery bounce</h1>
<h3>Default</h3>
<div id="box-1"></div>
<h3>{pixels: 40, duration: 1, direction: 'alternate', timing_function: 'ease-in-out'}</h3>
<div id="box-2"></div>
<h3>{duration: 0.7, timing_function: 'cubic-bezier(30,10,30,10)'}</h3>
<div id="box-3"></div>
<h3>Pasa el mouse sobre la siguiente imagen ...</h3>
<img id="img" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEsomZLE4xMMymwuehFoP1YS9-lZwWcdySyJ9cDSXWBAybrBhEAJoDf8RKMn8MvSPfyfp5eGEVkgBzvKv7o2dn7_iru_BtFgossaTVa8yNU0UpjM2s9-MIFhI0aMr-MI6u7Dzyf8PROKs/s1600/jquery.png" />
</body>
</html>


jueves, 10 de septiembre de 2015

jQuery rotate - Rotación de elementos con jQuery y CSS3 Animations


Hola, en esta ocasión os traigo un método (rotate) que sin duda os va a servir para dar rotación a cualquier elemento que necesitéis, todo ello gracias a CSS3 animations, elegante y configurable a vuestro gusto a través de la posibilidad de modificar sus propiedades: duration, delay, iteration_count, direction y timing_function. Los posibles valores para cada una de estas propiedades son los que ya vienen descritos en CSS3 animations. Por defecto el plugin viene configurado de la siguiente forma:

 var defaults = {
  duration: 1,
  delay: 0,
  iteration_count: 1,
  direction: "normal",
  timing_function: "linear"
 };


A continuación podéis ver algunos ejemplos de animación con jQuery rotate:


jQuery rotate basado en CSS3 animations

Básico

Propiedades: {duration: 3, delay: 3, iteration_count: "infinite", timing_function: "ease"}

Propiedades: {duration: 1, delay: 1, direction: "reverse", iteration_count: "infinite", timing_function: "ease-in"}

Propiedades: {duration: 1, delay: 0, direction: "alternate", iteration_count: 4, timing_function: "ease-in-out"}




El código fuente del plugin con los ejemplos ...

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>

<script>

(function($){ 
/* Author: Manu Dávila | Web: http://jquery-manual.blogspot.com */
 $.fn.rotate = function(options){
 var defaults = {
  duration: 1,
  delay: 0,
  iteration_count: 1,
  direction: "normal",
  timing_function: "linear"
 };
 if (options === undefined){options = defaults;}
 if (options.duration === undefined) {options.duration = defaults.duration;}
 if (options.delay === undefined) {options.delay = defaults.delay;}
 if (options.iteration_count === undefined) {options.iteration_count = defaults.iteration_count;}
 if (options.direction === undefined) {options.direction = defaults.direction;}
 if (options.timing_function === undefined) {options.timing_function = defaults.timing_function;}
 
 
 animation = "animation"+Math.floor((Math.random() * 1000000000000000) + 1);
 
 this.find(".style-rotate").remove();
 
 //Normal
 this.append("<style class='style-rotate'>@keyframes " + animation + " {from {transform: rotate(0deg);} to {transform: rotate(360deg);}}</style>");
 this.css("animation-name", ""+animation+"");
 this.css("animation-duration", ""+options.duration+"s");
 this.css("animation-delay", ""+options.delay+"s");
 this.css("animation-iteration-count", ""+options.iteration_count+"");
 this.css("animation-direction", ""+options.direction+"");
 this.css("animation-timing-function", ""+options.timing_function+"");
 //webkit: Chrome, Safari, Opera 
 this.append("<style class='style-rotate'>@-webkit-keyframes " + animation + " {from {-webkit-transform: rotate(0deg);} to {-webkit-transform: rotate(360deg);}}</style>");
 this.css("-webkit-animation-name", ""+animation+"");
 this.css("-webkit-animation-duration", ""+options.duration+"s");
 this.css("-webkit-animation-delay", ""+options.delay+"s");
 this.css("-webkit-animation-iteration-count", ""+options.iteration_count+"");
 this.css("-webkit-animation-direction", ""+options.direction+"");
 this.css("-webkit-animation-timing-function", ""+options.timing_function+"");
 //moz: firefox 
 this.append("<style class='style-rotate'>@-moz-keyframes " + animation + " {from {-moz-transform: rotate(0deg);} to {-moz-transform: rotate(360deg);}}</style>");
 this.css("-moz-animation-name", ""+animation+"");
 this.css("-moz-animation-duration", ""+options.duration+"s");
 this.css("-moz-animation-duration", ""+options.delay+"s");
 this.css("-moz-animation-iteration-count", ""+options.iteration_count+"");
 this.css("-moz-animation-direction", ""+options.direction+"");
 this.css("-moz-animation-timing-function", ""+options.timing_function+"");
 };
})(jQuery);

 $(function(){
  $("#box-1").rotate();
  $("#box-2").rotate({duration: 3, delay: 3, iteration_count: "infinite", timing_function: "ease"});
  $("#box-3").rotate({duration: 1, delay: 1, direction: "reverse", iteration_count: "infinite", timing_function: "ease-in"});
  $("#btn").on("click", function(){
   $("#box-4").rotate({duration: 1, delay: 0, direction: "alternate", iteration_count: 4, timing_function: "ease-in-out"});
  });
 });
</script>

<style>
 #box-1{
  width: 150px;
  height: 150px;
  background-color: orange;
 }
 
 #box-2{
  width: 150px;
  height: 150px;
  background-color: green;
 }
 
 #box-3{
  width: 150px;
  height: 150px;
  background-color: pink;
 }
 
 #box-4{
  width: 150px;
  height: 150px;
  background-color: yellow;
 }
</style>

</head>
<body>
<h1>jQuery rotate basado en CSS3 animations</h1>
<h3>Básico</h3>
<div id="box-1"></div>
<h3>Propiedades: {duration: 3, delay: 3, iteration_count: "infinite", timing_function: "ease"}</h3>
<div id="box-2"></div>
<h3>Propiedades: {duration: 1, delay: 1, direction: "reverse", iteration_count: "infinite", timing_function: "ease-in"}</h3>
<div id="box-3"></div>
<h3>Propiedades: {duration: 1, delay: 0, direction: "alternate", iteration_count: 4, timing_function: "ease-in-out"}</h3>
<button id="btn">Click me!!</button>
<div id="box-4"></div>
</body>
</html>


jQuery - selector eq() para acceder a elementos de un modo indexado


Hola, hoy veremos un simple ejemplo de uso del selector eq() en jQuery, este selector nos permitirá acceder a los elementos de un modo indexado, es muy útil por ejemplo para recorrer todos los elementos de una clase, o acceder individualmente a ellos, igualmente para acceder a los elementos de un determinado tag html.

El ejemplo consiste en que el usuario a través de un input number pueda seleccionar el index de un elemento li, el elemento li seleccionado recibirá una clase css que resaltará su estado como activo.

Selecciona el index:
  • li 0
  • li 1
  • li 2
  • li 3


Código fuente del ejemplo ...

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>

<script>
 $(function(){
  $("#input-list").on("change", function(){
   //Eliminar la clase li-active para reiniciar la búsqueda
   $("#list li").removeClass("li-active");
   //Obtener el número index introducido por el usuario
   index = $(this).val();
   //Si el elemento existe
   if ($("#list li:eq("+index+")").length)
   {
    //Agregar la clase li-active al elemento
    $("#list li:eq("+index+")").addClass("li-active");
   }
  });
 
 });
</script>

<style>
 .li-active {
  color: yellow;
  font-weight: bold;
 }
</style>

</head>
<body>
<h3>jQuery - selector eq() para acceder a elementos de un modo indexado</h3>

Selecciona el index: <input type="number" id="input-list" min="0" max="3" value="0">

<ul id="list">
<li>li 0</li>
<li>li 1</li>
<li>li 2</li>
<li>li 3</li>
</ul>
</body>
</html>


miércoles, 9 de septiembre de 2015

jQuery - método accordion para crear efecto persiana


Hola, en esta ocasión vamos a ver como podemos crear un método jQuery que nos permita emular un efecto persiana sobre determinados elementos, el objetivo es que podamos pasar este método (accordion) a un elemento, por ejemplo, un button y que al hacer click sobre el mismo se muestro u oculte un determinado contenido, el método accordion contendrá tres argumentos, el primero (element) el cual utilizaremos para indicar el elemento que obtendrá el efecto persiana, el segundo (options) opcional para indicar opciones como pueden ser visible para decidir si el elemento será visible o no de inicio y duration para indicar la velocidad de la animación y y finalmente un tercero (callback) para poder incluir una llamada una vez ha finalizado la animación.

Aquí puedes ver un ejemplo del efecto persiana al hacer click sobre el botón:



Hello World


Código fuente del ejemplo:

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
  
  <script>
 
 $.fn.accordion = function(element, options, callback){
 
  defaults = {
   visible: false,
   duration: 400
  };
  
  if (options === undefined){options = defaults;}
  if (callback === undefined){callback = function(){}}
  
  if (!options.visible){$(element).css({display: "none"});}
  
  $(element).addClass("accordion");
  
  this.on("click", function(){
   $(element).slideToggle(options.duration, function(){
   callback();
   });
  });
 };
  
  
    $(function(){
  $("#btn-1").accordion("#box-1", {visible: false, duration: 800}, function(){console.log("Hello World");});
    });
    </script>
  
 </head>
 <body>
   <button type="button" id="btn-1">Accordion</button>
   <div id="box-1">
  <div>Hello World</div>
  <div><a href="#">Link</a></div>
   </div>
 </body>
</html>


Extracting url data from a textarea with jQuery and Javascript


Hello, today you can see one example of how to extract url data from a textarea with jQuery and Javascript, the objetive is detect the keyup event from textarea element and to use the match() method from javascript for url indexing with a regular expression, finally, to show the html link with the finding.


  • Simple demo, write one url, example: https://www.google.com or http://www.google.com.es or http://google.com/home/index.php ...





Example code

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
  
  <script>
     $(function(){
   //Keyup event
   $("#textarea").on("keyup", function(){
    
    //Get the textarea text
    text = $(this).val();
    //find urls
    res = text.match(/http(s)?\:\/\/(www\.)?[a-z0-9\-\.]+[^www\.](\.[a-z]{2,4})[a-z0-9\/\-\_\.]*/i);
    //Yes results
    if (res !== null)
    {
     //Build the link
     $("#link-result").text(res[0]).attr("href", res[0]);
    }
    else
    {
     //Nothing
     $("#link-result").text('').attr("href", '');
    }
   });
     });
    </script>
  
 </head>
 <body>
   <textarea id="textarea" style="height: 150px; width: 100%;"></textarea>
   <div id="result">
   <a href="#" id="link-result" target="_blank"></a>
   </div>
 </body>
</html>


martes, 8 de septiembre de 2015

Extraer url de un textarea con jQuery y Javascript


Hola, en esta ocasión veremos un ejemplo de como extraer una url de un textarea mezclando un poco de jQuery y Javascript. La intención es detectar el evento keyup del textarea para ir realizando una búsqueda con el método match() de Javascript pasando como argumento una expresión regular preparada para indexar urls, si ha sido encontrada alguna url, mostrar la primera coincidencia en un link. Este básico ejemplo puede servir para implementar los típicos loaders de los comentarios que podemos encontrar en plataformas como Facebook ó Twitter, una buena idea como siempre es utilizar la teconolgía AJAX para procesar la url en el servidor por ejemplo con PHP.


  • Simple demostración, escribe alguna url tipo: https://www.google.com ó http://www.google.com.es ó http://google.com/home/index.php ...





Código del ejemplo

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
  
  <script>
   $(function(){
    //Evento que ocurre cuando se suelta la tecla
    $("#textarea").on("keyup", function(){
     
     //Obtener el texto del textarea
     texto = $(this).val();
     //Realizar una búsqueda de urls en el textarea
     res = texto.match(/http(s)?\:\/\/(www\.)?[a-z0-9\-\.]+[^www\.](\.[a-z]{2,4})[a-z0-9\/\-\_\.]*/i);
     //Si hay resultados
     if (res !== null)
     {
      //Mostrar la primera url encontrada
      $("#link-resultado").text(res[0]).attr("href", res[0]);
     }
     else
     {
      //De lo contrario no mostrar nada
      $("#link-resultado").text('').attr("href", '');
     }
    });
   });
  </script>
  
 </head>
 <body>
 <textarea id="textarea" style="width: 100%; height: 150px;"></textarea>
 <div id="resultado">
  <a id="link-resultado" href="" target="_blank"></a>
 </div>
 </body>
</html>


Reemplazar todas las coincidencias de una palabra completa con Javascript


A continuación podréis ver un ejemplo práctico de como reemplazar todas las palabras completas de un texto con Javascript, para tal tarea crearemos una expresión regular con la palabra a buscar entre los caracteres especiales \b (Word Boundary), esto nos permitirá limitar la búsqueda a sólo palabras completas, en este caso, si por ejemplo queremos buscar la palabra "ola" en un texto, "hola", "caracola", ... serán ignoradas y es requisito que la palabra sea "ola" exclusivamente. A la expresión regular también le incluiremos las condiciones "i" e "g", "i" para ignorar mayúsculas y minúsculas, por ejemplo, "oLa", "Ola", "olA", .. son válidos y "g" para buscar-indexar todas las coincidencias.


<script>
	window.onload = function(){
		texto = document.getElementById("texto").innerHTML;
		//la condición "i" en la expresión regular ignora mayúsculas y minúsculas
		//la condición "g" en la expresión regular busca todas las coincidencias
		buscar = /\bzapato\b/gi;
		reemplazar = "Javascript";
		document.getElementById("resultado").innerHTML = texto.replace(buscar, reemplazar);
	};
</script>

<h3>Reemplazar todas las coincidencias de una palabra completa con Javascript</h3>
<div id="texto">
	zapato gazapato mato Zapato gato arrebato pato gato zaPato zapatón
</div>
<h3>El Resultado</h3>
<div id="resultado"></div>


martes, 11 de agosto de 2015

Crear aplicaciones móviles con HTML5, CSS3 y Javascript







Autor: Telmex Hub

Título: Aprende a crear aplicaciones móviles multiplataforma con HTML5, CSS y Javascript.

Descripción:

Será un día dedicado a conocer proyectos y herramientas creadas e impulsadas por Mozilla con la finalidad de que los asistentes aprendan a hacer web de una manera fácil y divertida con Webmaker, así como para los asistentes con un nivel intermedio, aprendan a realizar aplicaciones para móviles multiplataforma basadas en HTML5, CSS y JavaScript.

Otras sugerencias ...

DESARROLLO DE APLICACIONES MULTIPLATAFORMA (D.A.M.) | EXPLICACIÓN SOBRE EL CICLO Y OPINIÓN
Sesión 1: Freelanceando con Joombla
Creamos una App Móvil con Javascript en Directo - Framework MVC Alloy
Html básico en cómputo en la Nube
Desarrollar Aplicaciones Android con Dreamweaver CS6
APP INVENTOR: APRENDE TODO LO QUE DEBES SABER DESDE 0 | CREAR APP DESDE 0 | TUTORIAL COMPLETO
24 Aplicaciones reales hechas en Javascript
Sesión 1: Freelanceando con Joombla
Sesión 1: Agilidad para el Desarrollo de software con Scrum. (Parte 2)
Going Mobile? Aprende cómo crear aplicaciones nativas para dispositivos móviles con GeneXus
Aprende a crear la Web
Backbone.js, desarrolla aplicaciones en Javascript (Curso completo)
Desarrollo de apps móviles multiplataforma
Batalla de Código 2do día
Como Crear Apps Nativas, Android, iPhone, iPad, Html5
Desarrollo de aplicaciones móviles híbridas con framework Ionic y AngularJS
Curso: Desarrollo de WEB Apps con HTML5 y JQuery Mobile 4/4
CPCO5 - Livecode. Desarrollo ágil de aplicaciones móviles multiplataforma
VIDEO TUTORIAL CRACION WEB MOVIL HTML5 EN 1 MINUTO
Curso java avanzado 4: Clases abstractas y polimorfismo

lunes, 10 de agosto de 2015

1 - Node.js - Mi primer servidor







Autor: Uriel Hernández

Título: 1- Node.js - Mi primer servidor.

Descripción:

Si no sabes qué es un servidor un framework:

http://dxvtuts.com/blog/articulo.php?...

El día de hoy nos iniciaremos en el mundo de node.js una de las tecnologías más modernas, poderosas y con un futuro enorme en el desarrollo.

¿Por qué aprender node.js es indispensable? Explico eso en una entrada de mi blog:

http://dxvtuts.com/blog/articulo.php?...

Entra aquí a la página de node.js para instalarlo:

http://nodejs.org/

Visita html5facil, para aprender más todos los días:

http://html5facil.com/

Visita Quod Graphic:

http://www.quodgraphic.com/

Otras sugerencias ...

Primeros pasos en Express, framework web para Node.js #jsIO
Chat con Node.js + Express + Socket.io
Websockets con Socket.io
Crea un servidor con Express + Node.js
Acceder a la cámara y el micrófono con HTML5
Primeros pasos con SailsJS en español #jsIO
Aprende Node.js desde Cero: Instalación de Node.js + NPM + Express
Introducción a NoSQL - Edgar González (español)
Introducción a nodeJS #nodeIO
Websockets y tiempo real en NodeJS #nodeIO
Que es grunt? (en solo 20')
Curso de NodeJS en español para programadores de PHP - 01
Conexión a base de datos con Nodejs Mysql
Curso de Node.js , Express y Mongodb: Iniciando con Node.js
Trabajando Node JS con bases de datos (MongoDB)
02.- Curso de node.js. Node Interactivo con REPL
Learn Node.js (Level 1)
Nodejs - Mi primer servidor web
Primeros Pasos con Nodejs Español
Nodejs #3 Creando nuestra primera "clase" en Javascript