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

featured like me   Make Your Own Tweet/Like/+1 To Unlock System with jQueryGoing 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.

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   Make Your Own Tweet/Like/+1 To Unlock System with jQuery

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   Make Your Own Tweet/Like/+1 To Unlock System with jQuery

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.

The comments were closed because the article is more than 180 days old.

If you have any questions related to what's mentioned in the article or need help with any computer issue, ask it on MakeUseOf Answers—We and our community will be more than happy to help.

25 Comments -

0 votes

TechnoAngina

Wow, this is actually really surprisingly useful! Thanks!

0 votes

Salim B

the test.html file is corrupt it is 144 bytes only and an empty html file

0 votes

MakeUseOf TechGuy

You’re right, sorry – reuploaded, should be fine now.

0 votes

Mehul

No James. still it is “0″ byte file. please re check. thanks

0 votes

MakeUseOf TechGuy

Gyyaaaa, sorry – that’s the CDN cached copy! Try now, I’ve cleared the cache…

0 votes

Nurlan

You are a liar!!! (test.html)

0 votes

MakeUseOf TechGuy

Excuse me? Care to elaborate on what you’re having issues with before you start throwing abuse my way?

0 votes

Nurlan

You are a liar!!!

0 votes

James William

Good job! But I just want to edit the buttons Google + and Facebook to be

Every time I try to make those little changes, the hidden Div refuses to appear. Any idea?

0 votes

James B

Can you paste your code somewhere? Kind of difficult to tell you whats wrong without actually seeing it.

0 votes

James William

Good job! But I just want to edit the buttons Google + and Facebook to be
<g:plusone href="http://refinerypedia.blogspot.com&quot; size="tall" callback="plusOned"</g:plusone
<fb:like data_href="https://www.facebook.com/Refining&quot; send="false" width="95" show_faces="true" layout="box_count" font="verdana"” from the codes to pass your security system.

0 votes

James William

Your system hide any html codes! I’ll remove the close”>” from the following codes
<g: plusone href="http://refinerypedia.blogspot.com&quot; size="tall" callback="plusOned"
</g: plusone
<fb: like data-href="https://www.facebook.com/Refining&quot; send="false" width="95" show_faces="true" layout="box_count" font="verdana"
</fb: like

1 votes

James William

Too long time to have comments moderated

1 votes

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.

0 votes

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.

0 votes

Mahmoud M

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

0 votes

James B

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

0 votes

Brennan

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

0 votes

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.

0 votes

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?

0 votes

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.

0 votes

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?

0 votes

HackYa

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

0 votes

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#_=_

0 votes

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?