Creating a simple jQuery plugin for Pinterest

Plugins play a great part in the success of jQuery. There are hundreds of them out there, and having the ability to create your own is a great skill to have. With all of the interest in Pinterest (no pun intended), I thought it would be a good idea to do up a quick and simple Pinterest sharing plugin for jQuery.

Getting started

First we need to grab the jQuery plugin boilerplate

(function( $ ) {
    $.fn.pinterest = function(options) {
        
        var settings = $.extend( {                    
        }, options);
        
        return this.each(function() {    
        
        });

    };
})( jQuery );

This boilerplate provides us with the ability to specify default configuration values (settings) and ensures that the infamous jQuery chaining ability is maintained (the return this.each). I’m going to take advantage of the default configuration values by specifying the default Pinterest image we’ll be using. This can be overridden when initializing the plugin by specifying the url to the preferred image.

Default image


Custom image

pinterest-alt

(function( $ ) {
    $.fn.pinterest = function(options) {
        
        var settings = $.extend( {
            'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png'
        }, options);
            
        return this.each(function() {    
        
        });

    };
})( jQuery );

$(document).on('ready', function(){
    $('img#share').pinterest({ button: 'pinterest-alt.png'});
});

Now that we have a basic framework done, let’s start adding some functionality. We need to update the this.each function to initialize each image and add some events for us. I’ve chosen to have the icon hover over the image being shared. To do this, I need to wrap the image in a span element that positioned ‘relative’, I then need to append the share image and position it absolutely. I’m going with the bottom right, but feel free to have a play

(function( $ ) {
    $.fn.pinterest = function(options) {
        
        var settings = $.extend( {
            'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png'
        }, options);
                    
        return this.each(function() {    
            img = $(this);
            img.wrap('<span class="pin-it" style="position: relative;" />');
            img.parent('span.pin-it').append('<img src="' + settings.button + '" style="display: none;position: absolute; bottom: 20px; right: 20px;cursor: hand; cursor: pointer;" />');
        });
    };
})( jQuery );

$(document).on('ready', function(){
    $('img#share').pinterest({ button: 'pinterest-alt.png'});
});

Now that the elements that we need are there, we can start attaching our events. I’m going to use the hover and click events. When the user hovers over the main image, the share button will appear.

(function( $ ) {
    $.fn.pinterest = function(options) {
        
        var settings = $.extend( {
            'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png'
        }, options);
        
        function on_click () {         
        };
        
        function on_hover_in() {
            $(this).siblings('img:first').show(500);
        };    
        
        return this.each(function() {    
            img = $(this);
            img.wrap('<span class="pin-it" style="position: relative;" />');
            img.parent('span.pin-it').append('<img src="' + settings.button + '" style="display: none;position: absolute; bottom: 20px; right: 20px;cursor: hand; cursor: pointer;" />');
            img.hover(on_hover_in);
            img.siblings('img:first').on('click', on_click);
        });

    };
})( jQuery );

$(document).on('ready', function(){
    $('img#share').pinterest({ button: 'pinterest-small.png'});
});

The on_click event looks like the following

function on_click () {
    img = $(this).siblings('img:first');
    description = img.attr('title');
    url = document.location;
    media = img.attr('src');

    var pin_url = 'http://pinterest.com/pin/create/button/?url=' + encodeURIComponent( url ) +
        '&media=' + encodeURIComponent( media ) +
        '&description=' + encodeURIComponent( description );
    
    window.open(pin_url, 'Pin - ' + description, 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
    $(this).hide(1000);
};

It’s grabbing the image we want to share, and then reading it’s title and src attributes. It’s also getting the current pages url using document.location. The Pinterest share url has 3 parameters that we are interested in:

  • url – the page we are sharing from
  • media – the image we want to share
  • description – the text we want to share with the image

When I’m creating the share url, I’m also using the JavaScript encodeURIComponent function to make sure the values are properly escaped.

One final thing we need to allow for is if the image src url is relative or not. If it’s relative we’ll need to update the media url to be fully qualified.

function getUrl(src){
    var url = document.location.toString();
    var http = /^https?:\/\//i;
    if (!http.test(src)) {
        if(src[0] == '/'){
            url = url.substring(0, url.lastIndexOf('/')) + src;
        } else {
            url = url.substring(0, url.lastIndexOf('/')) + '/' + src;
        }
    } else {
        url = src;
    }
    
    return url;
};

This function is checking to see if the provided src URL starts with http or not. If it doesn’t it then creates an absolute url and returns it.

And that’s it, we now have a fully functional jQuery plugin for sharing images on Pinterest. You can see the full HTML and JavaScript or download it below. The image I’m sharing by the way is Picasso’s Three Musicians

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Creating a simple Pinterest! jQuery</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        
    <script type="text/javascript">    
        
        (function( $ ) {
            $.fn.pinterest = function(options) {
                
                var settings = $.extend( {
                    'button' : 'http://business.pinterest.com/assets/img/builder/builder_opt_1.png'
                }, options);
                
                function getUrl(src){
                    var url = document.location.toString();
                    var http = /^https?:\/\//i;
                    if (!http.test(src)) {
                        if(src[0] == '/'){
                            url = url.substring(0, url.lastIndexOf('/')) + src;
                        } else {
                            url = url.substring(0, url.lastIndexOf('/')) + '/' + src;
                        }
                    } else {
                        url = src;
                    }
                    
                    return url;
                };
                
                function on_click () {
                    img = $(this).siblings('img:first');
                    description = img.attr('title');
                    url = document.location;
                    media = getUrl( img.attr('src') );
    
                    var pin_url = 'http://pinterest.com/pin/create/button/?url=' + url +
                        '&media=' + media +
                        '&description=' + description;
                    
                    window.open(pin_url, 'Pin - ' + description, 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
                    $(this).hide(1000);
                };
                
                function on_hover_in() {
                    $(this).siblings('img:first').show(500);
                };
                    
                return this.each(function() {    
                    img = $(this);
                    img.wrap('<span class="pin-it" style="position: relative;" />');
                    img.parent('span.pin-it').append('<img src="' + settings.button + '" style="display: none;position: absolute; bottom: 20px; right: 20px;cursor: hand; cursor: pointer;" />');
                    img.hover(on_hover_in);
                    img.siblings('img:first').on('click', on_click);
                });

            };
        })( jQuery );
    </script>    
</head>
<body>
<div id="page">
    <!-- [banner] -->
    <header id="banner">
        <hgroup>
            <h1>Creating a simple Pinterest! jQuery</h1>
        </hgroup>        
    </header>
    <!-- [content] -->
    <section id="content">
        <img id="share" src="picasso.jpg" title="Three Musicians" />
    </section>
    
    <script>
        $(document).on('ready', function(){
            $('img#share').pinterest({ button: 'pinterest-small.png'});
        });
    </script>
</div>
<!-- [/page] -->
</body>
</html>

SHARE THIS POST
  • Sean Meyer

    That’s pretty cool. I’ve only ever done one jQuery plugin myself and that was just something simple to see if I could do it. I did take you source code and modify it just a little bit. I noticed that with your source code, the “pin it” image stays on the image when the mouse is no longer hovering over the image. So I changed it up just a little bit so that when the mouse is no longer hovering over the image, the “pin it” image hides again. I know you were just going with a simple how-to of creating a jquery plugin but to me it seemed like it would be just a little bit better to have that button hide again so that it’s not always on there.

    All I did was change the “img.hover(on_hover_in);” line to “img.parent(‘span.pin-it’).hover(on_hover_in, on_hover_out);”. Then I altered the on_hover_in function to read, “$(this).children(‘img:last’).show(500);”. I had to make it be “children” instead of “siblings” because I changed the hover event to be based on the span that was wrapped around the main image. Then I created an “on_hover_out” function that does the same thing as the “on_hover_in” except to hide the button.

    It’s a nice little effect. I didn’t fully test this out (with the actual clicking on an image to make sure everything goes good) because I personally don’t have a pinterest account and at the moment I didn’t feel like joining it either.

    • Jonny Schnittger

      Glad to see you extended it :)

  • http://www.webdesign.org/ Julia Agnes

    nice tutorial)

  • pavan bangaram

    Good information.. Thanx for providing program..!

  • http://www.kizipapa.com/ Kizi 3

    This article is exclusive, original and interesting. you’ve captured my attention your use of persuasive language and logical points. thanks for this convenient information. i will be back to browse lots of of your articles.

  • http://cdeutsch.com/ Christopher Deutsch

    Thank you for this!! Exactly what I was looking for!

    Do you have an associated license for this? If not, I’m partial to MIT.

    Do you mind if I modify it and put it on GitHub? I’ll credit you and link back to your blog of course.

  • kaqil1988

    4b – The Last years I used to be really, really low on $$ and debits were killing me from all angles. that was UNTIL I decided to generate money.. on the Internet! I landed on surveymoneymaker point net, and started doing surveys for straight cash, and surely i’ve been much more able to pay my bills! I’m so happy, that I did this.. – t1EG