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:

<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.

Ads by Google

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.

Ads by Google
Comments (25)
  • Dan

    This is an awesome article! I know it’s a bit old but I had a quick question, anyway to make all 3 required? Kind of like this company does here : http://superglued.com/masonjennings#_=_

    • James B

      Sure. Define three new globals (somewhere at the start of the code), like:

      facebokShared = false;
      googleShared = false;
      twitterShared = false;

      Then inside of each respective share event listener, set those to “true”. For example, inside the plus one event, before trigger our custom event, you would put:

      googleShared = true;

      Now, in the custom event coding, replace the URL check statement with

      if(googleShared && twitterShared && facebookShared)

      So the secret.show() funciton will only be called if all of the networks have been shared.

      Got it?

  • HackYa

    You are like the funniest developer I’ve encountered. (I mean that in a good way.)

  • SJeev

    Hello,

    I don’t know if i am missing something, but I can’t see the share buttons for this article to get the demo file downloaded. Could any one help me with that?

  • Brennan

    Hello, I have included the Javascript and everything but my buttons do not appear?
    What would most likely be the problem?

    • James B

      Did you download the demo files and compare to those? That would be the easiest. Otherwise, please post a URL so I can check out the source.

    • Brennan

      Well, that was my bad. I didn’t download the demo files and I placed the JavaScript in the wrong location.

      The Twitter and Google + are working fine but the Facebook button doesn’t even show up. I even tried coping and pasting the code. What am I missing?

    • James B

      Please share a URL where I can check your code and error console. I really can’t say what you’re doing wrong without seeing anything.

  • James

    My question in other words… Can I identify a url for the +1 button and a fan page for FB button? I tried to add some tags like “href” for +1 and “data-href” for FB but the result was that the hidden div refused to appear. pls help.

    • James B

      This line:

      if(e.url == window.location.href){

      checks if the URL that was shared is the same as the current URL in the browser. So that’s why it isn;t showing. You would need to adjust that to either manually specify a URL, or just trust the logic and remove the check completely. So try:

      /* Listen for the pageShared event and ignore URL */
      $(document).on(‘pageShared’,function(e){
      $(“.secret”).show();

      });

      or

      /* Listen for the pageShared event and check for specific URL as well*/
      $(document).on(‘pageShared’,function(e){
      if(e.url == window.location.href || e.url == “http://yourfacebookfanpageurl.com”){
      $(“.secret”).show();
      }
      });

      instead.

    • Mahmoud M

      Unfortunately, I tried all codes above but still have the problem

    • James B

      Please share you code, Mahmoud. It’s unlikely you have the same problem as this user.

Load 10 more
Affiliate Disclamer

This review 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.
Affiliate Disclamer

This review 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.