Make Your Own Tweet/Like/+1 To Unlock System with jQuery

Ads by Google

featured-like-meGoing viral used to mean a disease epidemic, but now it’s something all content creators crave. You could rely on the quality of your content alone – if it’s good enough, people will share it, right? Maybe. But you could also help things along a little by offering something extra of value to those who do share – a coupon, a download, a smiley face sticker in the mail, or a stock image of a cute kitten. Today I’ll show you how to create your own like/tweet/+1 to unlock system with a little jQuery and the native APIs.

This method is for people who have their own websites and would like the unlock mechanism on there. If you’re looking to do this on your Facebook page, the basic Facebook fan gate tutorial may be more useful.

How It Works

We’ll be loading a set of buttons from the various networks and attaching to their respective events or callbacks to indicate when something was shared. A callback is a function that runs when something else has finished, usually passed in as a parameter to another function. When using jQuery AJAX for example, a success callback is run when the AJAX query has been successful – it does something with the returned data, like acknowledging receipt of form data. We’ll also be using events – which are a little more complex, but out of the scope of this tutorial. We’ll then trigger our own event, which contains the code to reveal one or more secret parts of the page. For our purpose, just hiding a bit of content and revealing it should be sufficient, but you could adjust this to be a little more secure that loads via AJAX or similar.

Requirements:

  • jQuery should already be included and loading in the header of your page. I’m not going to cover that today.
  • You should know how to include Javascript on the page, whether that be through inline script tags or in a separate .JS file linked in the header.

Basic Share Buttons

Let’s start by loading a basic set of share buttons on the page. There are two parts to this, firstly to load the JS for the buttons (we’re using asynchronous version of these to avoid blocking the page load). Here’s the codes from all three networks – you needn’t separate these into little snippets, they can all go together in one JS file.

 
/* Facebook */
(function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      status     : true,                                
      xfbml      : true                                 
    });
};

/* Twitter */
  window.twttr = (function (d,s,id) {
  var t, js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
  js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
  return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));

/* Google Plus */
(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();

Next, place these where you like the buttons to appear:

Ads by Google
<fb:like send="false" width="95" show_faces="true" layout="box_count" font="verdana"></fb:like>
<a href="https://twitter.com/share" data-via="w0lfiesmith" data-count="vertical"></a>
<g:plusone size="tall" callback="plusOned"></g:plusone>

Remember to change the data-via attribute to your own Twitter user. Also, note the presence of a callback parameter on the plusOne button – there is no event to attach to here, just a callback when the button is clicked.

Finally, create a new CSS class definition for “.hidden“, and set the display:none property for it. Anything you want to hide until shared should go in here.

Make sure your buttons are loading at this point.

basic-buttons

Attaching To Share Events

Here’s the real magic. Let’s start with Facebook. After the FB.init function, use FB.Event.subscribe as follows:

 
FB.Event.subscribe('edge.create', function(href, widget) {
        $.event.trigger({
            type: "pageShared",
            url: href
        });
 });

Here we’re asking to listen to the edge.create event (fired when a user likes the page). We’re then triggering our own jQuery event that I’ve called pageShared, and passing in the href value as the URL that was shared. We’ll be checking this later. Your complete Facebook button code should now look like:

 
window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      status     : true,                                
      xfbml      : true                                 
    });

    FB.Event.subscribe('edge.create', function(href, widget) {
        $.event.trigger({
            type: "pageShared",
            url: href
        });       
    });
};

Next, Twitter. twttr.events.bind is used here (you can attach to a follow event too if you like), but the important thing to remember is that these all need to be wrapped in the twttr.ready callback. Again, we’re triggering the same jQuery pageShared event, passing in the correct variable to represent URL that was shared.

 
twttr.ready(function (twttr) {
    twttr.events.bind('tweet', function (event) {
        $.event.trigger({
            type: "pageShared",
            url: event.target.baseURI
        });
    });
});

Finally, Google Plus. Remember earlier I explained that there are no events for plusOne, so instead we’ve specified a callback function. Let’s now create that function and trigger the pageShared event from there.

 
function plusOned(obj){
     $.event.trigger({
         type: "pageShared",
         url: obj.href
     });
}

Show Me The Money

Finally, we need to attach to our custom pageShared event as follows:

 
/* Listen for the pageShared event */
$(document).on('pageShared',function(e){
       if(e.url == window.location.href){
                $(".secret").show();
       }
});

Very simply, if the URL passed in is the same as the current page, we show the secret content to the user. In the example I made, a kitten. You lucky people!

unlocked-kitten

I’m Lazy. Can I Download Your Complete Demo?

To download the complete demo file for this tutorial – yep, you guessed it – just share the page using the buttons on the side there and the download link will be magically revealed to you.

Problems with the code? Let me know in the comments, but a liberal dollop of console.log will help you to understand what objects are being passed back to you and the secrets they contain; and be sure to use the exact button codes supplied here, as some formats (like iFrame) don’t work with these events.

Affiliate Disclamer

This article may contain affiliate links, which pays us a small compensation if you do decide to make a purchase based on our recommendation. Our judgement is in no way biased, and our recommendations are always based on the merits of the items.

For more details, please read our disclosure.
New comment

Please login to avoid entering captcha

Log In