Where to Start with jQuery Selectors

With jQuery there are many ways to select elements. We are going to cover two of the most popular selectors id and class.

jQuery uses the same selectors as CSS. This makes it very easy to select the elements you want to work with. The two most commonly used selectors are id and class. So before we start make sure you have your jQuery setup and the $(document).ready() function on the page.

Selecting by ID

This is best used when you want to target one specific element. The selector is exactly the same as what you would use to set styles for the particular element in CSS.

Selecting element with CSS and setting some styles.

#youridhere {
	display: none;
}

Now selecting the same element with jQuery and adding CSS styles.

$("#youridhere").css("display","none");

Selecting by Class

With the class selector you can select multiple elements at once. jQuery deals with multiple elements in a very simple manor. It returns an array of jQuery objects. With the way jQuery is designed it will automaticaly apply anything you do to your selection to all elements without having to loop threw the results.

Lets take a simples example of hiding all elements with a class of hide. To do this with CSS we would create the class in our style sheet like so:

.hide {
	display: none;
}

To do this same thing to all the elements with the class of hide in jQuery. You would use the following statement:

$(".hide").css("display","none");

This should get you started on the path of using jQuery in your projects. To read more about the selectors your can use in jQuery check out the documentation.

jQuery's document.ready(), What is it and Why is it Useful?

The document.ready() function is the first thing anyone should learn about jQuery. This function will allow you to take all that ugly behavioral javascript out of your markup.

Lets face it, nobody likes all those javascript:void(0); in the anchors href. As for that body “onload” function call, can that too, its no good. All that ugly code in the markup is just plain bad news.

With jQuery and document.ready() you can put all your event driven javascript in one file, making it easy to maintain and upgrade later. The document.ready() function works just as the name implies. Document refers to the DOM, or Document Object Model, while in this case “ready” refers to when the DOM is registered by the browser.

Before we start, make sure you have jQuery included on your page. For a quick refresh on how that’s done, click here.

Using the document.ready() function is really easy. Check out this example:

	$(document).ready(function(){
		//insert code here
		alert("this will flre when the DOM is loaded.");
	});

As with most code, there is a shorthand version of the document.ready() function. In jQuery, any function passed to the jQuery object will be bound to the document.ready() function, as seen below.

	$(function(){
		//insert code here
		alert("this will work the same as the code above.");
	});

This is how you would add a click event to all the anchor tags on your page using the document.ready() function.

	$(document).ready(function(){
		$('a').click(function(){
			alert("you clicked me!");
		});
	});

That’s all there is to it. Are you having an issue with jQuery, or any code you need some help on? Have an idea for an article you’d like to see? Feel free to leave a comment with any questions or suggestions.

Adding Twitter to your site with jQuery Part 2

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. In Part 2 we will add some simple CSS to the tweet to make it look nice, and display all the data the twitter API returns.

As a special bonus for all four of you who will read this post, i’ve also built this into a jQuery plugin. First we will start by changing what we did in the last post a bit by creating a unordered list to hold the tweets.

	var $tweetContainer = $(document.createElement("ul"))
                                         .attr("id","tweet-cont")
       					.addClass("tweet-cont");
	base.$el.append($tweetContainer);

We will use each list item to hold the tweet data. I added an if statement that will add a class to easily style even and odd tweets, and then we add the code to include the users Twitter avatar and the tweet text.

	var tweetClass = "odd";
	if(i%2 == 0){
		tweetClass = "even";
	}

     var $tweet = $(document.createElement("li"))
                  .attr("id","tweet_"+tweets[i].id)
                  .addClass(tweetClass)
                  .addClass("tweet");
     $tweetContainer.append($tweet);

     var $tweetPhoto = $(document.createElement("img"))
                  	 	.addClass("avatar")
                  	 	.attr("src",tweets[i].profile_image_url);
     $tweet.append($tweetPhoto);

     var $tweetDesc = $(document.createElement("div"))
                  	 	.addClass("text")
                  	 	.html(""+tweets[i].from_user+": " + base.replaceURLs(tweets[i].text));
     $tweet.append($tweetDesc);

You’ll notice there’s a function in there called replaceURLs:

	base.replaceURLs = function(text){
		text = text.replace(base.options.aTagRegexp,"$1");
		text = text.replace(base.options.userRegexp,"$1@$2");
		text = text.replace(base.options.hashtagRegexp,"$1#$2");
		return text;
	}

This function will search through the text of the tweet and take urls and make them clickable, as well as finding twitter users and hash tags and linking those correctly as well.

Now we need to display when the tweet was created. That should be too bad right, we just create an element and use it to display the date. Normally when working with dates i’d say that was OK, except twitter is all about instant gratification. We want to know what’s happening and how long ago it was when it happened. Its for this reason we need a little extra code so we can display when a tweet was created in relation to the current time.

First we need to get some values to compare the tweets created date against:

	var minDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*1000));
	var hourDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*60*1000));
    	var dayDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(24*60*60*1000));

Then all we need to do is write our compare logic. The seconds and minutes are obvious choices, but choosing when to stop displaying a message like “2 days ago” vs displaying the tweet date is up to you. For the plugin I went with 5 days. We will also be providing a link to the app used to post the tweet, very helpful considering there are about 800,000 different apps out there.

	if(minDiff < 59){
		timeDiff = "
about "+minDiff+" minutes ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(hourDiff < 24){ timeDiff = "
about "+hourDiff+" hours ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(dayDiff < 5){ timeDiff = "
"+dayDiff+" days ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else{ var AMPM = "PM"; var myHours; if(tweetDate.getHours() < 12){ AMPM = "AM"; if(tweetDate.getHours() == 0){ myHours = "12"; }else{ myHours = tweetDate.getHours(); } }else{ myHours = tweetDate.getHours()-12; } var myDate = tweetDate.getDate() +"th"; if(tweetDate.getDate() == 1 || tweetDate.getDate() == 21 || tweetDate.getDate() == 31){ myDate = tweetDate.getDate() +"st"; }else if(tweetDate.getDate() == 2 || tweetDate.getDate() == 22){ myDate = tweetDate.getDate() +"nd"; }else if(tweetDate.getDate() == 3 || tweetDate.getDate() == 23){ myDate = tweetDate.getDate() +"rd"; } timeDiff = "
"+myHours+":"+tweetDate.getMinutes()+" "+AMPM+" "+base.months[tweetDate.getMonth()]+" "+myDate+" from "+base.fixEncHTML(tweets[i].source)+"
"; }

Finally, we can add a couple useful links that will help users view and reply to the tweets:

	var $tweetLinks = $(document.createElement("div"))
					.addClass("links")
                  	 	.html("Reply · View Tweet");

	$tweet.append($tweetLinks);

Thats all it takes to write out a tweet, al this code will get you something that looks like this (i know, the colors are awful):

tweets example.png

That was a bunch of code. I hope you enjoyed this series of posts, and I promise if I ever do a series of posts again i’ll write them all first before posting :-)

Check out this quick demo and of course, the plugin source code.

jQuery 101: Adding jQuery to Your Website

Everyone has to start somewhere. So lets get you setup to begin learning jQuery. The first thing you will need to do is get jQuery setup and running on your site. Now let’s get started.

The traditional jQuery Setup

1. Download the files

Make a trip over to the jQuery site and download the latest version or follow this link to the download page. You will want to grab the minified version of the code to save on bandwidth.

2. Add the script to your site

In the root folder of your site make a new folder called js. Then add the freshly downloaded jQuery script file to this folder. With the files in place you will need to add the script to your pages.

Open up one of you pages on your site and make you way to the head section of the page. Now copy the script tag below and paste in the head area of your files.


Once your script tag is in place you are ready to start using jQuery.

Using hosted files from Google

Google offers a great service. They host several of the most popular javascript library’s. This works well for sites that want to save on bandwidth or always have to latest code. Google offers several different ways to link to the script files. We are just going to use the direct link method. For more on the options of linking to these files check out the Google AJAX Libraries API.

1. Choose your version

There are a few options you have for choosing what version of jQuery you would like to link to. You can link to the main version of 1. This will keep your code updated to any subversions of 1. You could link to 1.3 this would keep your site running on the latest subversion of 1.3. Lastly you can link directly to the version you want to use.

Link to current subversion of version 1

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

Link to current subversion of version 1.3

http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js

Link to current version 1.3.2

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

Link to older version 1.3.1

http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js

2. Add the script to your site

I recommend you link to the current version that you know works with all of your code. So below is the script tag that you can place in the head section of your site. The script tag loads the current version as of this posting jQuery 1.3.2.


This will get you started on your path to learning jQuery. Look for more jQuery basics to come and also check out some of the resources listed below.

Adding Twitter to your site with jQuery Part 1

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. Part one we will go over the basic of the Twitter API and look at some simple code that will print out a list of tweets.

For this example I will use my own tweets, feel free to follow me @jaredharbour.

What is Twitter?

In recent years, social media has become a huge part of peoples lives. Sites like MySpace, Facebook and LinkedIn (which I sometimes refer to as ‘The Big Three’) allow people from all over the world connect and share their lives and ideas instantly. Recently Twitter has become the next big addition to the global conversation. Twitter is unique among the others in that its only function is to accept and display 140 character “micro-blogs”. Let me get one thing out of the way before we continue, micro-blogging doesn’t mean every message has to be about taking out the trash and mowing the lawn. There are 5 million+ Twitter users in the world today, and that number will only get bigger. Now lets get into some code.

The Twitter API

The Twitter API attempts to conform to the principals of Representational State Transfer or REST. I’ll leave it to you to read up on what that means, simply put it means that with the Twitter API you simply need to change the extension to get your results in a different format.

http://search.twitter.com/search.format

Since we just want to print out a list of tweets, we will start by using the search function. The search function will return its results in two formats, XML and JSON. We will use JSON because in my experience it’s faster and easier to use than XML.

http://search.twitter.com/search.json

For a more in depth look at the search function take a look at the Twitter documentation. Now lets get to the jQuery part. We get to use one of my favorite methods jQuery gives us, jquery.getJSON. This handy function will return the JSON via a GET HTTP request, just what the doctor ordered.

$.getJSON(
    'http://search.twitter.com/search.json?callback=?&rpp=25&q=from:jaredharbour',
    function(data) {
        // our code to handle the data here
    }
);

That’s not all though, we need to get at our data. jQuery makes it easy with the each function. This will let us loop through the JSON object with ease. In this case, “tweets” becomes our array of data. Then we need to check a few things to make sure we are in the section of the object we want. This logic isn’t perfect, but it will work for all the major browsers. The first and second if statements are to check if there are tweets to look at. I needed them both because it seems IE was unhappy with accessing the first element, because in some cases there isn’t one. The third if statement makes sure that what we’re looking at is in fact a tweet, and not some random piece of data.

$.each(data, function(i, tweets){
	if (tweets.length != undefined){
		if (tweets[0] != undefined){
			if (tweets[0].created_at != undefined){

			}
		}
	}
});

Now we just need to print out some data. Just a simple for loop and a document.write and we’re all set.

for(var i = 0; i < tweets.length; i++){
    document.write("
"+tweets[i].text+"
"); }

That’s all there is to it! In the next post I will get into formatting the tweets to add more functionality. Here are some of the topics I will cover later in the series.

  • Hyperlinking hash tags and users
  • Formatting tweet time and date
  • Linking to the Twitter app

Have a question? Looking for something specific? Leave a comment and I’ll get back to you!

We're attending the jQuery Conference!

That’s Right! We are signed up to join 298 other web professionals in Cambridge for this years jQuery Conference. The conference will be held September 12th and 13th at Microsoft New England Research and Development Center in Boston, MA.

We are really excited. We are waiting to see what topics are going to be covered, but we know there will be a 3 hour seminar for jQuery beginners that at least one of us will check out. We are also looking forward to meeting other people in the area who use jQuery, maybe exchange some ideas about jQuery or even the web in general.

If you want some information about this years jQuery conference, check out some of the links i’ve listed below. Also check back here for more updates, as we will be posting any new information when we get it. We will also be posting our live feedback while at the conference via Twitter. Follow @think2loud for all the updates.

UPDATE!

Keep up with the details of the jQuery Conference here. Only a month to go!