Cómo hacer la animación del like de Twitter en CSS3

Hace unos cuantos meses Twitter introdujo un nuevo botón de like (corazón) en sus tuits, sustituyendo así el clásico fav al cual ya estábamos acostumbradísimos. Adoro la manera en la que Twitter ha implementado el efecto cuando haces clic en el corazoncito, es una animación curradísima y muy vistosa. En este artículo te explicaré cómo implementarlo en tus proyecto utilizando CSS3 y jQuery. Si quieres agregar esta fantastica animación en tus proyectos personales, estate atento a este sencillo tutorial. Es muy interesante.

Código HTML

Muestra las noticias del feed basándote en el ID del mensaje de la base de datos.

<div class="feed" id="feed1">
Social Network Script http://thewallscript.com
<div class="heart " id="like1" rel="like"></div> 
<div class="likeCount" id="likeCount1">14</div>
</div>

<div class="feed" id="feed2">
OAuth Login http://oauthlogin.com
<div class="heart" id="like2" rel="like"></div>
 <div class="likeCount" id="likeCount2">10</div>
</div>

.......
.......
.......

Imagen del corazón

Para implementar la animación, tendrás que utilizar esta imagen. Para descargarla haz clic con el botón derecho sobre la imagen y pulsa en Guardar como...

Código CSS

Con esto mostraremos el primer frame de la animación del corazón.

.heart {
background: url(images/web_heart_animation.png);
background-position: left;
background-repeat: no-repeat;
height: 50px;
width: 50px;
cursor: pointer;
position: absolute;
left:-14px;
background-size:1450px; //actual background size 2900px
}
.heart:hover
{
background-position: right; //displaying last heart frame 
}
.likeCount
{
margin-top: 13px;
margin-left: 28px;
font-size: 16px;
color: #999999
}

Animación CSS

Aquí tienes el código para animar la imagen de fondo frame por frame.

@-webkit-keyframes heartBlast 
{
0% {background-position: left;}
100% {background-position: right;}
}

@keyframes heartBlast 
{
0% {background-position: left;}
100% {background-position: right;}
}

.heartAnimation 
{
-webkit-animation-name: heartBlast; //webkit broswers
animation-name: heartBlast;
-webkit-animation-duration: .8s;
animation-duration: .8s;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-webkit-animation-timing-function: steps(28); //background frames count 28
animation-timing-function: steps(28);
background-position: right;
}

Puedes modificar las funciones de timing basándote en tus frames del background.

Código Javascript

Basándonos en la sentencia $("body").on('click','.heart',function(){}, diremos que heart es el nombre de la clase del tag div. Utilizando $(this).attr("id") haremos referencia al valor ID del tag.

<script src="jquery.min.js"></script>
<script>
$(document).ready(function()
{

$('body').on("click",'.heart',function()
{
var A=$(this).attr("id");
var B=A.split("like"); //splitting like1 to 1
var messageID=B[1];
$(this).css("background-position","")
var D=$(this).attr("rel");

$.ajax({
type: "POST",
url: "message_like_ajax.php",
data: dataString,
cache: false,
success: function(data)
{
$("#likeCount"+messageID).html(data);
if(D === 'like') 
{
$(this).addClass("heartAnimation").attr("rel","unlike"); //applying animation class
}
else
{
$(this).removeClass("heartAnimation").attr("rel","like");
$(this).css("background-position","left");
}
}); //ajax end

});//heart click end

});
</script>

message_like_ajax.php

Contiene el código PHP para guardar los datos tanto de los likes como de los dislikes.

include 'db.php';
if(isSet($_POST['msg_id']) && isSet($_POST['rel']))
{
$msg_id=mysqli_real_escape_string($db,$_POST['msg_id']);
$rel=mysqli_real_escape_string($db,$_POST['rel']);
$uid=$session_uid; // User login session id
if($rel=='Like')
{
//---Like----
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)==0)
{
$query=mysqli_query($db,"INSERT INTO message_like (msg_id_fk,uid_fk) VALUES('$msg_id','$uid')");
$q=mysqli_query($db,"UPDATE messages SET like_count=like_count+1 WHERE msg_id='$msg_id'") ;
$g=mysqli_query($db,"SELECT like_count FROM messages WHERE msg_id='$msg_id'");
$d=mysqli_fetch_array($g,MYSQLI_ASSOC);
echo $d['like_count'];
}
}
else
{
//---Unlike----
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)>0)
{
$query=mysqli_query($db,"DELETE FROM message_like WHERE msg_id_fk='$msg_id' and uid_fk='$uid'");
$q=mysqli_query($db,"UPDATE messages SET like_count=like_count-1 WHERE msg_id='$msg_id'");
$g=mysqli_query($db,"SELECT like_count FROM messages WHERE msg_id='$msg_id'");
$d=mysqli_fetch_array($g,MYSQLI_ASSOC);
echo $d['like_count'];
}
}
}

Fuente: 9lessons.info

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP
ARTÍCULO ANTERIOR

SIGUIENTE ARTÍCULO