Cómo crear un plugin de jQuery para hacer pin en Pinterest

Pinterest ha ido creciendo hasta convertirse en uno de las redes sociales más populares del mundo. Nos permite organizar y compartir todas las cosas bonitas que encontramos en la web. Me pareció muy útil, sobre todo, a la hora de buscar inspiración en el diseño de interiores, la decoración y otros menesteres artísticos.

Como habrás notado, en la actualidad, el botón de Pin it de Pinterest puede encontrarse en la mayoría de sitios web de diseño. También lanzaron un bookmarklet que escanea una página web para detectar las imágenes y permitir “pinearlas” fácilmente. Pero no creo que esto último sea muy útil, sobre todo cuando la página contiene más de 30 imágenes. Tardarás un rato hasta que encuentres la imagen adecuada. Como resultado de esto, he creado este plugin que te permite pinear una imagen inmediatamente.

Este plugin aparecerá en todas las imágenes, y está dentro de un contenedor que vienen con el típico botón de Pinterest, Pin it. Así, el visitante sólo tiene que pasar el cursor por encima de la imagen que quiera, y podrá pinearla inmediatamente. Es un plugin simple.

HTML

No requiere de ningún código HTML, básicamente sólo tienes que incluir los archivos CSS y Javascript:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.pinit.js"></script>
<script type="text/javascript">
$(function () {

	$('img').pinit();

});
</script>

CSS

Puedes personalizar el plugin con CSS. He creado 2 imágenes semi transparentes (blanco y negro), así que siéntete libre de intercambiarlas. El CSS es bastante simple, la mayoría de los estilos son para los botones.

.pinit {
	position:relative;
	display:inline-block;

}

/* pin it overlay style */
.pinit .pinit-overlay {
	position:absolute;
	top:0;
	left:0;
	width:100%;
	height:100%;
	z-index:200;
	display:none;
	background:transparent url('../images/semi-white.png') repeat 0 0;
	text-align:center;
}

/* button style, and center it */
.pinit .pinit-overlay a {
	position:relative;
	top:50%;
	left:50%;
	margin:-10px 0 0 -21px;
	display:block;
	width:43px;
	height:20px;
	background:transparent url('../images/pinit-button.png') no-repeat 0 0;
	text-indent:-9999em;
}

.pinit .pinit-overlay a:hover {
	background-positon: 0 -21px;
}

.pinit .pinit-overlay a:active {
	background-position: 0 -42px;
}

Javascript

No hay nada complejo en la sección de Javascript de más abajo. Básicamente, estamos haciendo un plugin que envuelve a cada una de las imágenes con el span .pinit y añadiendo un poco de HTML para hacer el efecto de superposición con el botón PINIT. El botón PINIT estará vinculado a la URL de compartir de Pinterest:

http://pinterest.com/pin/create/bookmarklet/?media={MEDIA_URL}'&url={URL}&is_video={IS_VIDEO}&description={DESC}

(function($){
	
    //Attach this new method to jQuery
    $.fn.extend({ 
         
        pinit: function(options) {
 
			var defaults = {
				wrap: '<span class="pinit"/>',
				pageURL: document.URL
			} 		
 			
 			var options = $.extend(defaults, options);
			var o = options; 
			
            //Iterate over the current set of matched elements
            return this.each(function() {
				
             	var e = $(this),
             		pi_media = e.data('media') ? e.data('media') : e[0].src,
             		pi_url = o.pageURL,
             		pi_desc = e.attr('title') ? e.attr('title') : e.attr('alt'),
             		pi_isvideo = 'false';
             		bookmark = 'http://pinterest.com/pin/create/bookmarklet/?media=' + encodeURI(pi_media) + '&url=' + encodeURI(pi_url) + '&is_video=' + encodeURI(pi_isvideo) + '&description=' + encodeURI(pi_desc);
					
				var eHeight = e.outerHeight();				
             		e.wrap(o.wrap);
             		e.after('<span class="pinit-overlay" style="height: ' + eHeight + 'px"><a href="' + bookmark + '" class="pinit-button">Pin It</a></span>');
				
				$('.pinit .pinit-button').on('click', function () {				
					window.open($(this).attr('href'), 'Pinterest', 'width=632,height=253,status=0,toolbar=0,menubar=0,location=1,scrollbars=1');				
					return false;
				});     
				
				$('.pinit').mouseenter(function () {
					$(this).children('.pinit-overlay').fadeIn(200);
				}).mouseleave(function () {
					$(this).children('.pinit-overlay').fadeOut(200);
				});

				
            });
      
        }
        
    });

})(jQuery);

Fuente: queness.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP