All posts tagged jQuery

Displaying Your Tweets On Your Website With jQuery

Today we’re going to be back with our good old friend, jQuery. What we’re going to be doing is something that has become almost part-and-parcel of any website, especially a portfolio/blog site for individuals, which is to display your most recent tweets. Today we’re going to look at how easy jQuery makes this process. Of course, when using Javascript, there is a chance the user has it turned off, but for most people they will see a nice list of tweets. Beware, I am presuming you have an intermediate knowledge of jQuery.

Today we’ll write the code and package it up into a neat little, reusable function. Check out the Demo before we get started. In a future tutorial, we will look at converting it into a jQuery plugin.

Include jQuery

So, firstly, we will add jQuery to head of our page. By now you should be pretty comfortable doing this. I always use Google’s CDN:

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

And now you want to add some blank script tags in which will go our code.

<script type="text/javascript" charset="utf-8">
	//code goes here
</script>

When Ready

Of course, we only want this code to run once the DOM is loaded. jQuery has its own ready function to make sure this happens:

$(document).ready(function() {
		//code goes here
});

Most of you will probably know that, however what many don’t realise is that we can shorten it:

$(function() {
	//code goes here
});

There is no speed benefit to using either, and if you prefer the first, it’s fine to use it.

Set up the HTML

Don’t worry, we’re nearly onto the fun bit! My HTML looks like so:

<div id="tweets">
		<h3 id="error">There was a problem fetching tweets</h3>
		<h3 id="preload">Currently loading your tweets...</h3>
	</div>

I have two headings, one with an id of “error”, and the other with id “preload”. With CSS, I hide the “preload” heading, so that when the user loads the page, only the first heading (the “error”) is shown.

This is where we can get sneaky – with jQuery, the first thing we’ll do is get rid of the “error” heading, and display the “preload” heading. It’s really easy:

$('#error').remove();
$('#preload').show();

The idea here is that if Javascript is not on, none of that happens and the user just sees the error. If it is on (and consequently we will go ahead fetching the tweets) then the user gets the preloading header.

Fetching your Tweets

The first thing we’re going to do is create an unordered list which we will put our tweets in:

var html='<ul>';

Next up is the fun bit. Getting your tweets. We’re going to use JSON (Javascript Object Notation). You can find out more about it at json.org. For the most part however, you don’t need to worry about how it works. You’ll find most sites support the fetching of data via JSON, including Twitter.

The URL to fetch your data looks like this:


http://twitter.com/status/user_timeline/Jack_Franklin.json?count=5&callback=?

There are two bits we can change there. The first obviously is the username. Mine is “Jack_Franklin”, but if you wanted your own, replace “Jack_Franklin” with your id. (Later on in this article we will make this a lot easier). The second bit to change is the section “count=5″. This sets the number of tweets to return.

You may wonder about the final part “&callback=?”. This page at Clientcide explains it well.

JSONP is a means by which to get JSON data from another domain than the one your page is on. If you try and use Ajax to request data from a different domain than the page, you’ll get a security error.

Essentially, without that bit, we could not request data from a domain other than our own. Remember earlier, when I said you don’t need to worry about how it works? This is an example of that.

$.getJSON

We’re going to be using the jQuery function getJSON(). getJSON is not really a function in its own right, it acts as a wrapper for $.ajax(), but makes things much simpler for us. getJSON takes two parameters:

$.getJSON(feed url, callback function)

We’ve already got our feed URL, so lets save it to a variable, pass it in and then set up our function:

var tweetFeed = 'http://twitter.com/status/user_timeline/Jack_Franklin.json?count=5&callback=?'
$.getJSON(tweetFeed, function()
{
});

Our callback functions needs to be passed the data that was returned, so that we can use it from within the function. You might think this is going to be really complex, but it’s not. We’re going to pass in a variable and this variable will contain the data. This variable can be called anything, jQuery does the rest. I tend to call mine “d” for “data”. You can call it “data” if you wish to be more verbose. It’s up to you. Call it “chicken” if you like. Our appended function looks like so:

$.getJSON(tweetFeed, function(d)
{
});

Process!

So, for each item, we need to process it. The data returned is an object that we can loop through using jQuery’s each() method:

	$.each(d, function(i,item)
				{

				})

So jQuery’s each() function takes two paramters – the data we want to iterate for (which in our case is the variable d, containing our data), and the second is a function to run. Our function looks like this:

function(i, item) {..}

Here i is the iteration variable, every time you loop through the data i gets increased. The second is a variable each item will be passed to through the iterations. So on our first loop, item contains the value of the very first item. On our next iteration, it contains the value of the second, and so on. Each item contains lots of data, the below text is all the data the very first returned tweet contains:

{"in_reply_to_status_id":null,"in_reply_to_screen_name":null,"contributors":null,"place":null,"favorited":false,"source":"<a href=\"http://twitter.com\" rel=\"nofollow\">Tweetie for Mac</a>","geo":null,"coordinates":null,"user":{"following":true,"description":"jQuery is my cocaine.","listed_count":47,"statuses_count":8833,"profile_use_background_image":true,"profile_background_color":"352726","show_all_inline_media":false,"followers_count":781,"contributors_enabled":false,"profile_background_image_url":"http://a3.twimg.com/profile_background_images/13458527/bg.jpg","profile_text_color":"3E4415","profile_image_url":"http://a1.twimg.com/profile_images/400484737/Photo_2-1_normal.jpg","friends_count":603,"profile_background_tile":false,"profile_link_color":"D02B55","url":"http://www.jackfranklin.co.uk","screen_name":"Jack_Franklin","geo_enabled":false,"notifications":false,"time_zone":"London","favourites_count":4,"protected":false,"follow_request_sent":false,"lang":"en","created_at":"Sun Apr 06 09:31:28 +0000 2008","profile_sidebar_fill_color":"bec1bd","location":"Cornwall, England","name":"Jack Franklin","verified":false,"id":14314572,"utc_offset":0,"profile_sidebar_border_color":"ffffff"},"in_reply_to_user_id":null,"truncated":false,"created_at":"Sun Aug 08 21:15:57 +0000 2010","id":20655130616,"text":"Anyone figure when us subscribers are due a new .Net mag ?"}

Accessing the Data

So we know that all that data is passed to the item variable, but how do we access the individual items? The main one you will want to look for is the property “text”, which contains the tweet. We access this using the dot notation, like so: item.text; So, in our loop, we’ll just add each item to our unordered list, which we created way back at the beginning.

	$.each(d, function(i,item)
				{
					html+='<li>'+item.text+'</li>';
				})
				html+="</ul>";

And once the loop is over, we’ll round off our list with the closing tag. So, we now have a nice list, full with our five most recent tweets.

Displaying the Tweets

Finally we must display the tweets, and this is the code that does it:

$('#tweets').children('h3').fadeOut('fast',function() {

					$('#tweets').append(html);
				})

The code is very straight forward, firstly we find all the headers and fade them out, so our “tweets” div is empty. Once those headers are faded out, we run a callback function which adds our HTML to our twitter div.

All Done!

Congratulations! You can now display your tweets using jQuery. But there’s one more bit. We’re going to wrap this up in a function and next time, we will convert it into a plugin.

This is what I’ve done:

function showTweets(elem, username, number)
	{
		var html = '<ul>';

	var tweetFeed = 'http://twitter.com/status/user_timeline/' + username + '.json?count=' + number + '&callback=?'
		$.getJSON(tweetFeed, function(d)
		{

			$.each(d, function(i,item)
			{
				html+='<li>'+item.text+'</li>';
			})
			html+="</ul>";

			elem.children().fadeOut('fast',function() {

				elem.append(html);
			})
		})
	}

There’s a couple of changes – firstly, we pass in the element, username and the number of tweets we want to display. We all hide all the given element’s children, so we can make sure it’s completely blank before passing in the tweets (this is something we will certainly be improving when we make this into a plugin). The function is used like so:

	showTweets($('#tweets'), 'Jack_Franklin', 5)

Next time, as I said, we will make some changes and wrap this up as a jQuery plugin which is much better to reuse than a function, in my opinion. I’ll also post the plugin for download so you can use it in your own tweets.

A DEMO can be downloaded here.

jQuery: More Tips & Tricks

Load from Google CDN

Google’s CDN (Content Delivery Network) hosts jQuery for you to include on your site. The advantage of this is two-fold: firstly, if the user has visited other sites that loaded jQuery from the CDN (of which there are a lot) then they will already have a version of jQuery cached, which means it will not be needed to load again. Secondly, you can specify a certain version to load. For example, this code would load version 1.4.2:

<script type="text/javascript" src=http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

However, if I wanted to load the most recent version, I could just do this:

<script type="text/javascript" src=http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

That will include the most recent version, up to version 1.9.9. However this is not recommended, as an upgrade to jQuery may well break your scripts. It’s generally suggested that you stay within a version, for example:

<script type="text/javascript" src=http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

jQuery takes CSS Selectors

Remember, jQuery functions will take any valid CSS selector. But a selector can contain multiple selections. For example, you might do this:

$(elem).siblings("h2").hide();
$(elem).siblings("p").hide();

But why not just do this?

$(elem).siblings("h2,p").hide();

Chain over lines

Remember, white space means nothing in Javascript, so whilst you might have this:

$("elem").hide().addClass("something").show().attr("alt","something else").fadeOut("slow");

If you struggle to read that, you can do this as well:

$("elem")
	.hide()
	.addClass("something")
	.show()
	//etc etc etc

There’s no bonus in either performance wise, it’s just down to readability. A lot of people don’t realise they can split it over multiple lines.

More Context

I know I discussed context in my last article, but I wanted to add a bit more. Last time we discussed adding a context like so:

$("#someElem", "div");

I know that’s a poor example, but bear with me! When you do this, all jQuery does is call the find() function on the div and search for “#someElem”. So the above code gets translated into this:

$("div").find("#someElem")

Which way you use is totally up to you. Personally I find the 2nd method (using .find()) to be much easier to understand when quickly scanning a document, but it’s up to you.

Check if an Element Exists

This is more a quick code snippet, but if you wish to check if an element exists, it’s so easy!

if($("elem").length) {
//the element exists
}

If it does not exist, jQuery will just degrade gracefully, no errors, nothing bad happens.

Run onLoad

This is pretty common knowledge, but to make sure jQuery only runs once the DOM is ready to be manipulated, you need to call jQuery’s .ready() function:

$(document).ready(function() {
//code in here
}

What is perhaps not as well known is that you can shorten this:

$(function() {
//code here
}

Or alternatively, you can add all your javascript just before the closing tag and not need to bother with the onLoad code:

....all your normal code here
<!--then add your javascript here, firstly loading jQuery.js and then your code-->
</body>

Add a JS Class to the Body

An easy way to detect if Javascript is on is to add a class to the body, so the first line of your Javascript would be:

$(body).addClass("javascripton");

Whilst this might seem pointless from a Javascript view (if Javascript isn’t on you wont be able to check via an if statement), this is useful for CSS. You might have some elements that might change style, so any CSS styles that might change via Javascript, just add “.javascripton” in front of the styles in your css file.

Store information with jQuery’s data method

jQuery provides its own method for storing data to be used later on. To save some data is pretty easy:

$("elem").data("someVariable", 39);

And to return it:

$("elem").data("someVariable") //returns 39

I’ve seen people use all sorts of tags to store information to be used with their Javascript code, title tags, alt tags, rel tags, etc. Use this. Note: I believe HTML 5 may well include some form of data attribute, but for now, stick with this.

Surrender $

If you are using another library that uses the “$” symbol, jQuery allows you to pass that on to be used by the other library and still use jQuery:

jQuery.noConflict();
//now instead of $, use jQuery
jquery("elem").hide();

You can also make use of a closure. Whilst explaining this is slightly out of the scope of this tutorial, this is how you use it:

(function($) {
//in here, $ relates to jQuery
$("elem").hide()
})(jQuery)
//out here, $ does not relate to jQuery
$("elem").hide() //WILL NOT WORK
jQuery("elem").hide() //works

And that’s it.

I hope you’ve found these tips useful and helpful. I’m planning a lot more similar posts in the future. If you have any suggestions the best place to get in touch with me is Twitter – @Jack_Franklin.

Sequential Fade In – JQuery Plug-in

Sequential fade ins (the action of fading in elements one after the other) have the ability to draw the user’s attention to a certain portion of your content. They can also give a professional touch to your jQuery photo galleries. I have created a jQuery plug-in that makes the process of sequentially fading elements extremely simple.

Code + Documentation

(function(jQuery) {
jQuery.fn.fadeInSequence = function(fadeInTime, timeBetween)
{
	//Default Values
	timeBetween = typeof(timeBetween) == 'undefined' ? 0 : timeBetween;
	 fadeInTime = typeof(fadeInTime) == 'undefined' ? 500 : fadeInTime;

	//The amount of remaining time until the animation is complete.
	//Initially set to the value of the entire animation duration.
	var remainingTime = jQuery(this).size() * (fadeInTime+timeBetween);

	var i=0; //Counter
	return jQuery(this).each(function()
	{
		//Wait until previous element has finished fading and timeBetween has elapsed
		jQuery(this).delay(i++*(fadeInTime+timeBetween));

		//Decrement remainingTime
		remainingTime -= (fadeInTime+timeBetween);

		if(jQuery(this).css('display') == 'none')
		{
			jQuery(this).fadeIn(fadeInTime);
		}
		else //If hidden by other means such as opacity: 0
		{
			jQuery(this).animate({'opacity' : 1}, fadeInTime);
		}

		//Delay until the animation is over to fill up the queue.
		jQuery(this).delay(remainingTime+timeBetween);

	});	

};

})(jQuery);

.fadeInSequence( [ fadeInTime ], [ timeBetween ] )
fadeInTime: How long each element takes to fade in (in milliseconds)
timeBetween: How much time to wait before the next element fades in (in milliseconds)

The .fadeInSequence() method animates the opacity of the matched elements one element at a time.

The default value for fadeInTime is 500ms, and the default value for timeBetween is 0ms. The method is overloaded, so the following are all valid function calls.

$("wrapper p").fadeInSequence();             //Elements will each fade in over a duration of 500ms with no pause between each element
$("wrapper p").fadeInSequence(1000);       //Elements will each fade in over a duration of 1000ms with no pause between each element
$("wrapper p").fadeInSequence(300, 500);  //Elements will each fade in over a duration of 300ms with a 500ms pause between each element

Demo

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sequential Fade In</title>
<style type="text/css">
	#fadeIn{position: absolute;top: 10px;left: 10px;}
	#fadeInFadeOut{position: absolute;top: 10px;left: 100px;}

	#wrapper{margin-top: 50px; width: 330px;
			 height: 150px; border: 1px solid #000000;}

	#wrapper > *{margin-right: 10px; width: 100px; height: 100px;
				float: left; display: none;}

	#box1{background-color: #CCCCCC; left: 0px;}
	#box2{background-color: #FF0000; left: 110px;}
	#box3{background-color: #0000FF; left: 220px;}

</style>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.min.js'></script>
<script type="text/javascript" src="fadeinsequence.js"></script>

<script type='text/javascript'>
$(function(){ 

$("#fadeIn").click(function() {
	$("#wrapper").children().hide().fadeInSequence();
	});

$("#fadeInFadeOut").click(function() {
	$("#wrapper").children().hide().fadeInSequence().fadeOut();
	});

});
</script>

</head>
<body>
<div id="wrapper">
	<div id="box1">Box1</div>
    <div id="box2">Box2</div>

    <div id="box3">Box3</div>
</div>
<button type="button" id="fadeIn">Fade In</button>
<button type="button" id="fadeInFadeOut">Fade In+Fade Out</button>
</body>
</html>

The Fade In + Fade Out demonstrates that the queue is maintained for each element until the end of the entire .fadeInSequence() animation. This helps retain the “chainability” that we’ve grown to love with jQuery.

The plug-in was created with some simple math. In order to keep the queue equal between all animated elements, a varying delay was placed at the end of the fadeIn’s. This visual representation demonstrates how the plugin operates. In this example, the fadeInTime is set to 500 and timeBetween is also set to 500.
fadein

Questions? Comments? Bugs to Report? Give us your feedback in the comment section below.