Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

How to Create a Helpful Plugin With Twitter Anywhere

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

Twitter Anywhere is a "one-script-include" solution from Twitter to bring the power of their communication platform to your website. We'll be building a small jQuery script that utilizes Twitter Anywhere for your users.


Step 1: Registering Your Application

The first step in the Twitter Anywhere process is to create an application. The registration can be found here. The only field that might cause any level of confusion is the Callback URL. This is to be used when Twitter authenticates the user; it specifies where on your site you want to send the authenticated user back to. For most smaller applications, your website's homepage will likely be sufficient, however, for larger applications, you may want to direct the user back to an area that serves appropriate content for authenticated users.

One important setting worth noting is the Application Type. Now this won't appear in the Application creation process, but will be available by going to your apps, finding your new application, clicking the Settings tab next to Details, and changing the radio button from "Read Only" to "Read and Write" in the Application Type sections.

To be honest, it's embarrassing for me to admit how much time went by, while debugging, before I decided to look here!


Step 2: What's the Script Going to Do?

Using Twitter Anywhere, we're going to concentrate today on the Tweet Box feature. The Tweet Box provides excellent transparency between your website and Twitter, allowing users to tweet directly to their account without leaving your website, and, more importantly, continuing to interact with your content.

The jQuery script we're going to write today could easily be adapted into a jQuery or WordPress plugin. The script will detect the user highlighting a piece of text in say, your blog post, and display a "Tweet this" button. Once the user clicks this button, the script will take the highlighted text and call the Tweet Box function from Twitter Anywhere, inserting the highlighted text as the tweet body.

The user can then either leave the tweet as it is - with a link back to the page they're on - or they can edit any part of it before tweeting.

Security is vital here; the slightest bit of misuse, and the user will revoke access in their settings - and not likely return to give your application a second chance. So, always give the user a preview of exactly what will be posted to their account; it's generally a good practice to make them press the button before processing the tweet.

Tweeting Direct Image Links

The script will also allow for the user to click on any of your images, and achieve the same Tweet Box effect. In this particular instance, the tweet will reference the direct URL to the image.


Step 3: Setting Up the JavaScript Files

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="http://platform.twitter.com/anywhere.js?id=[API-KEY]&v=1"></script>
<script src="http://path-to-script/copybot/script.js"></script>

As you can see above, we need to include a few JavaScript files to make our plugin function correctly.

  • We'll be using jQuery for its ease of use and nice selector engine.
  • We'll use jQuery UI for basic user interaction; when the Tweet Box pops up, we can allow the user to drag it around with their mouse.

  • The next JavaScript include is the Twitter Anywhere file itself. Luckily for us, it's fairly lightweight, coming in at just over 7KB. As you can see, you'll need to supply your API key, which can be found in the Settings of the App page from earlier in this article.
  • The last file is our own script; this will hold all of our jQuery code and Tweet Box function calls.

Step 4: Beginning Our Code

$(document).ready(function(){

});

We'll start in our JavaScript file by containing everything within jQuery's document ready method. Everything in here will fire after the DOM has fully loaded, saving us from any potential errors.

function getSelectionText() {
    var text = "";

    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

The above piece of code will allow you to grab the highlighted text from the user once they have selected it. This code is a fairly standard function, and can be found (and documented) all over the internet.

$('.post').mouseup(function(){
	$('#tweetThis').show();
});

We can then begin to interact with the user with a mouse up event. In this particular page of HTML, I have created a div with a class of 'post'. For the tutorial, we are simply targeting this div so that the code doesn't run every time the user mouses up on the page. Once the user mouses up within this div, we will display a button to the user that allows them to tweet the highlighted text.

$("#anywhere").draggable();

This method uses jQuery UI to allow the user to drag the Tweet Box around at their leisure. We don't pass any options to it as the default functionality will suffice for what we're doing.

$('#tweetThis').click(function(){
		$('#tbox').empty();
		var text = getSelectionText();

		if(text != ''){
			twttr.anywhere(function (T) {
			    T("#tbox").tweetBox({
			      height: 100,
			      width: 400,
			      defaultContent: '"' + $.trim(text) + '" - ' + document.title + ' - ' + window.location.href
			    });
			});
		
			$('#anywhere').show();
			
		}

	});

Here is where the meat of our plugin's functionality will take place. On click of the "Tweet This" button, we will begin by emptying the contents of the Tweet Box. This allows the user to highlight a different piece of text and tweet that instead.

The next line will declare a variable to hold the user's selected text from our function call. We then do a quick check to determine if the user actually selected any text, and proceed with our Tweet Box initialization.

From the official documentation:

"The @Anywhere JavaScript file establishes a single global object (twttr). To use @Anywhere, call the anywhere method, and pass in a callback. The callback will receive an instance of the Twitter API Client (named "T" by convention) as its only argument. All @Anywhere features are available as members of the Twitter API Client."

This means that you can call any of these methods on the Twitter API Client ("T"): Auto-linkification of Twitter usernames, Hovercards, Follow buttons, Tweet Box, User login & signup. Your application can make multiple calls to the 'anywhere' method, so don't be afraid about limiting the functionality of your site!

As you can see, we then target "#tbox", to be filled with Twitter's Tweet Box feature. As you might have noticed, if you work with jQuery, it uses similar CSS selectors when querying the DOM.

If we were to call .tweetBox(); without any options, then the Tweet Box would take it properties from the defaults outlined in the Documentation. We use the defaultContent property to insert the user's selected text into a Tweet, along with the current page title and location. We use jQuery's $.trim function to get rid of any unwanted whitespace from the user's selection, which would cost them characters in their Tweet.

We can then display the created Tweet Box to the user, ready for them to approve and tweet!


Step 5: Tweeting Image URLs

$('img').click(function(){
	var url = $(this).attr('src');
	
	twttr.anywhere(function (T) {
 
	    T("#tbox").tweetBox({
	      height: 100,
	      width: 400,
	      defaultContent: 'Check out this image: ' + url
	    });
	 
	});
	
	$('#anywhere').show();

});

The code above provides the user with the ability to tweet a direct image URL to their account. We set up the Tweet Box exactly as before but, we use the 'src' of the 'img' element this time as the dynamic variable instead of highlighted text.
This could easily be adapted for HTML5 videos, if you desire to target them instead of images.

A Bit Little Housekeeping

$('#hide').click(function(){
	$('#tbox').empty();
	$('#anywhere').hide();
	$('#tweetThis').hide();
});

The above code simply allows the user to get rid of the Tweet Box after they have tweeted or if they change their mind about tweeting. We empty the div element ready for the next selected text or image URL.


Step 6: Possible Use Cases

This sort of functionality would lend itself perfectly to a blog.

Having this code adapted into a WordPress plugin would allow users to tweet quotes from your articles, increasing exposure and spreading your content across the internet.

The image URL tweeting would fit nicely on a photography or web design portfolio site where the user can tweet your pieces of work. Or, this script could be turned into a properly formed jQuery plugin for use on any website; static; CMS driven or Tumblr - the possibilities are endless.


Final Thoughts

The Twitter Anywhere platform is a fantastic way to layer Twitter functionality onto your site.

The Twitter Anywhere platform is a fantastic way to layer Twitter functionality onto your site. From personal experience, I think it is just that: a layer. I wouldn't feel comfortable building an entire application with it. The documentation is rather slim, and the first thing you may notice when using it yourself is how much potential it has, how much functionality could be in there, and how it's partially lacking right now.

For example, currently, you can retrieve a user's Favorites count - just the count, no content. This extra functionality would make Twitter Anywhere stand up level with the Server Side REST API that exists already, powering very complex, vast applications.

Good luck with this platform and try to find an interesting use case for some of its easy-to-implement features! In the meantime, check out the demo Copybot. Thanks for reading!

Advertisement