Monday, June 21, 2010

Using jQuery and Templating to Pull and Display Your Twitter Updates

A while back, I wrote a blog post on how to pull in your last three twitter posts into your web page via jQuery and JSON. It's still today a very popular post.

A lot has happened since that post and I wanted to re-address it and show you an alternative way of pulling in your Twitter feed via jQuery and the new Templating plugin developed by Microsoft. On the right is a new Twitter widget I put together using the new jQuery templating plugin.

Microsoft's Templating Plugin

During MIX10, John Resig and Microsoft announced that Microsoft would be contributing code back to the jQuery Project. One of their first contributions was the Templating plugin. Microsoft created templates for jQuery so that JavaScript developers could use jQuery to easily display a set of data.

The source code for the plugin can be found in the jQuery-tmpl GitHub repository. The plugin requires jQuery 1.4.2 or higher.

Getting Setup

Before we start you'll need the following:

Create a html page, and include jQuery, the template plugin and the supporting_methods.js. Then include the style.css doc so that your code from the demo we do looks nice.

The HTML

Since each tweet will be listed as a list item in an unordered list the only required HTML we need is an empty ul:

		<ul id="renderTweets"></ul>
	

In our demo though we want to make it a complete widget. We need some extra layout html to be able to provide a heading and a link to take you to more tweets. Here is the full html we'll use:

		<div id="Tweets">
			<h3>@RedWolves Tweets</h3>
		  	<ul id="renderTweets"></ul>
			<div id="more">
				<a href="http://twitter.com/redwolves">More &gt;</a>
			</div>
		</div>
	

Make sure you replace my twitter name, RedWolves, with yours.

Making the Ajax request

Now let's get the data from Twitter. We'll use a JSONP ajax call to get back the JSON data of the last three tweets from Twitter. To get the JSON data we will use the user timeline of the Twitter API.

		$("document").ready(function(){
			var url = "http://api.twitter.com/1/statuses/user_timeline.json?id=RedWolves&count=3&callback=?"
			$.ajax({
				dataType: 'jsonp',
				url: url,
				jsonpCallback: "renderTweets" 
			});
		});
	

At the end of the Twitter API url that we declare we attach the user id of the user timeline we want to see, in this case mine, RedWolves, so make sure to update with the username you wish to see. We then declare the url and call the .ajax() method and provide it with the dataType 'jsonp' so that we can pull the data via cross-domain. We set the url and then tell it which function we will call after the data is loaded. After the data is loaded we will call the function 'renderTweets', defined below, which will run the data through the template.

Defining the Template

Now let's define the template that will display the data we get back from the Ajax request. We define the template in a script tag and we provide it with a type of "text/template" and a unique ID.

		<script type="text/template" id="twitterTemplate">
			<li>
					<img src="${ user['profile_image_url'] }" /> 
					${ text.linkify().atify() } 
					<span class="created_at">
						${ relative_time(created_at) } via ${ source }
					</span>
			</li>
		</script>
	

On each JSON item we will run it through the template and create an li element with the profile photo, tweet text, when it was created and what source the tweet came from (e.g. Twitter for iPhone, web, etc.).

We are using a couple of supporting methods to help us in formatting. .linkify which will make any link a hyper link, atify which will link up any @screenname to their twitter profile and relative_time which will turn the created time into Twitter style time. You can find these methods in the supporting_methods.js file.

Putting it all together

The last bit of jQuery code we need to do is to actually call the plugin and combine the template with the data and put it into the DOM. Here we will define the renderTweets callback function.

		function renderTweets(data) {
			$("#twitterTemplate")
				.render(data)
				.appendTo("#renderTweets");
		}
	

What we do is select our template, call the template plugin method, .render, which takes in the data from the Ajax call and renders the results against the template, and then append the results to the desired element in the HTML, the ul with id of renderTweets.

The whole HTML

		<!DOCTYPE html>
		<html>
			<head>
				<meta charset=utf-8 />
				<title>twitter</title>
				<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
				<script src="jquery.tmpl.js"></script>
				<script src="supporting_methods.js"></script>
				<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
				<script type="text/template" id="twitterTemplate">
					<li>
							<img src="${ user['profile_image_url'] }" /> 
							${ text.linkify().atify() } 
							<span class="created_at">
								${ relative_time(created_at) } via ${ source }
							</span>
					</li>
				</script>
				<script type="text/javascript">
					$("document").ready(function(){
						var url = "http://api.twitter.com/1/statuses/user_timeline.json?id=RedWolves&count=3&callback=?"
						$.ajax({
							dataType: 'jsonp',
							url: url,
							jsonpCallback: "renderTweets" 
						});
					});

					function renderTweets(data) {
						$("#twitterTemplate")
							.render(data)
							.appendTo("#renderTweets");
					}
				</script>
			</head>
		<body>
		  <div id="Tweets">
			<h3>@RedWolves Tweets</h3>
		  	<ul id="renderTweets"></ul>
			<div id="more">
				<a href="http://twitter.com/redwolves">More ></a>
			</div>
		  </div>
		</body>
		</html>​
		
	



Source Code Demo

Saturday, April 03, 2010

Barcamp Rochester 2010 - Overview of jQuery UI and jQuery UI 1.8

Today was Barcamp Rochester 5. I gave a 30 minute overview of jQuery UI and went over the new features of jQuery UI 1.8. Here is the video of my talk I took with my flip video. Sorry about the sound quality, use headphones ;)

You can follow along with my slides. The slides are based off John Resig's HTML presentations and are heaviily modified to be jQuery UI themed and a showcase for what jQuery UI can do. (Note: you should use Safari/Chrome to view the slides. Also click the orange header text to advance the slide.)

If you attended my talk, please rate me on speaker rate.

Friday, January 22, 2010

jQuery 1.4 Give Us a New Way to Zebra Stripe

In jQuery 1.4 all setter methods have been extended to take in a setter function.  Before only .attr() had the ability to use a function to return the value to set. Now you can pass a setter function to .css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .before(), .after(), .replaceWith(), .wrap(), .wrapInner(), .offset(), .addClass(), .removeClass(), and .toggleClass().

The setter function can take two arguments, the index position of the element in the set and the old value of the element.

.css( propertyName, function(index, value))

With setter functions now available we can use this in a new way to zebra stripe a set of elements.  In this example we'll stripe a unordered list:

HTML:

<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
</ul>
jQuery 1.4:

$(document).ready(function(){
$("li").css("background-color", function(i){
return (i % 2 === 0) ? "#cccccc": "#FFFFFF";
});
});

We select all the LIs and call the .css() setter method. We give it the property name we want to update, background-image and we pass a function that will return the value we want to set.

The function tests if the index that we passed in i is MOD 2 (simply is it even or odd), if even set the color to #cccccc else set it to #FFFFFF.

Demo: (jsbin)

Note: Obviously, this isn't the best way to do zebra stripping with jQuery but I like to explore different ways to do the same thing to learn the techniques.

Monday, January 18, 2010

14 Days of jQuery - Behind the Scenes - yayQuery

14 Days of jQuery - Behind the Scenes - yayQuery from Ralph Whitbeck on Vimeo.

yayQueries Paul Irish steals my flip and records some video while we were out eating after day two of video recording.

Saturday, January 16, 2010

14 Days of jQuery - Behind the Scenes - Part 7

14 Days of jQuery - Behind the Scenes - Part 7 from Ralph Whitbeck on Vimeo.

The team feverishly works to get the Day 2 blog out before the stroke of midnight, everyone that is except...

Friday, January 15, 2010

14 Days of jQuery - Behind the Scenes - Part 6

14 Days of jQuery - Behind the Scenes - Part 6 from Ralph Whitbeck on Vimeo.

Ralph and Elijah are recording 6 podcasts while everyone is together. Here we are talking with Mike Hostetler and Jonathan Sharp about appendTo for a future episode.

14 Days of jQuery - Behind the Scenes - Part 5

14 Days of jQuery - Behind the Scenes - Part 5 from Ralph Whitbeck on Vimeo.

John Resig, Jonathan Sharp and Richard Worth are doing final sound checks. Here's a look at the set up.

Thursday, January 14, 2010

14 Days of jQuery - Behind the Scenes - Keynote

14 Days of jQuery - Behind the Scenes - Keynote from Ralph Whitbeck on Vimeo.

This is a look at the production team behind the keynote.

14 Days of jQuery - Behind the Scenes - Part 4

14 Days of jQuery - Behind the Scenes - Part 4 from Ralph Whitbeck on Vimeo.

Richard D. Worth and Jonathan Sharp are setting up the room for our live uStream with John Resig and other members of the jQuery team

14 Days of jQuery - Behind the Scenes - Part 3

14 Days of jQuery - Behind the Scenes - Part 3 from Ralph Whitbeck on Vimeo.

The team is finallizing the 1.4 release blog post. Heads are down and working feverishly to get it out.

14 Days of jQuery - Behind the Scenes - Eric Passmore

14 Days of jQuery - Behind the scenes - Eric Passmore from Ralph Whitbeck on Vimeo.

We sat down with Eric Passmore, Aol's Senior Vice President, Global Publishing Systems and talked about Aol. use of jQuery and thank him for the use of the facility.

14 Days of jQuery - Behind the Scenes - Part 2

14 Days of jQuery - Behind the Scenes - Part 2 from Ralph Whitbeck on Vimeo.

The team is finally together and waiting to head out to dinner.

Wednesday, January 13, 2010

14 Days of jQuery - Behind the Scenes - Part 1

14 Days of jQuery - Behind the Scenes - Part 1 from Ralph Whitbeck on Vimeo.

The team that came early is testing the video equipment at Richard D. Worth's house.

Heading to DC for the 14 Days of jQuery

I am currently sitting in the JetBlue terminal in JFK. I am on my way to Washington DC where I will meet most of the rest of the jQuery team and my jQuery Podcast cohost Elijah Manor.

We are going to be working on filming the talks and releases for the 14 Days of jQuery which starts tomorrow.

Elijah and I will be podcasting like mad men. Tomorrow we plan to interview John Resig about the jQuery 1.4 release and we do plan to release that episode on Friday. In addition to that episode we are planning to record four other episodes with other team members which we will release in the coming weeks. So much to look forward too.

Additionally to all the podcasting and video production for the 14 Days of jQuery, I'll be taking video's of "behind the scenes" and uploading them to ralphwhitbeck.com, so check back often or follow @jQueryPodcast Twitter account to see when new videos are posted.

The team is pretty excited to be able to bring the 14 Days of jQuery (not to mention a little tired) but I hope the community gets tons of value from all this work.

Saturday, January 02, 2010

Getting "Up-to-speed"

I was looking over my blog this week while I was out on holiday vacation and noticed I haven't posted a blog post since October.  So much has happened since then I think perhaps a "getting the reader up-to-speed" post is in order.  

So here we go...

jQuery Team member

Early last year, I made it a goal to blog, tweet and personally evangelize jQuery to better myself and the project.  My efforts got noticed by jQuery Evangelist Rey Bango and he brought me in as a advisor to the jQuery team.  While I was an advisor I took advantage of my situation and jumped in on projects the team was working on.  Mainly, the jQuery Conference in September and the Stack Overflow Dev Days talk in Toronto.

In November, it was voted on by the jQuery team to bring me on as a jQuery Team Member and I was added to the evangelism team.  I was truly surprised and honored by this action as I wasn't expecting it at the time. 

Being a team member made it easier for me to launch my new project...

The Official jQuery Podcast

I announced in October, at Stack Overflow Dev Days in Toronto, that I would be starting the Official jQuery Podcast in November.  I worked with the jQuery team to get infrastructure support and found a cohost, in Elijah Manor, that could give an outsiders perspective on topics.

We initially started with streaming the shows live on uStream.  But I think I am finding that to be too stressful and am reevaluating whether that is still viable.  Maybe at a later date.

Our first show, with guest John Resig, got the show ranked to #2 on the top Technology podcasts for the day which was very exciting.

We've since had guests Richard D. Worth, Paul Irish, Cody Lindley and Rey Bango.

Our planned shows for January will sure to be very exciting. We are planning to travel to Washington DC to do some shows live in person with the people we are going to interview.

You can find our show on iTunes or you can subscribe to the show with the raw RSS feed.

My plans for now are to do a weekly show as long as I can sustain them throughout 2010.

Coming up in 2010

I don't have many plans for 2010 at this point but there are a few things I am planning on.

We are currently in the middle of planning something huge for jQuery this month.  I'll be travelling with Elijah to cover the "something huge" for the Official jQuery Podcast.

In addition, there will be physical conferences in San Francisco, London and Boston.  I am hoping to at least attend the conferences that won't require a passport.
I am currently scheduled to give a talk on jQuery at LUGOR (Linux User Group of Rochester) on May 20th at RIT.

So there you go you should now be sufficiently "up-to-speed."

Sunday, October 25, 2009

My trip to Toronto and Stack Overflow DevDays 2009

On Wednesday, October 21st, 2009 I took the Amtrak train from Niagara Falls, NY to Toronto, Ontario, Canada.  I was going to speak at Stack Overflow DevDays in Toronto on Friday October 23rd.

I got there an extra day earlier then needed because of the time the train was going to get in on Thursday night I would of missed the speakers dinner.  But this extra time worked to my favor as I needed the extra time to work on finishing my slides and example code I was going to demo.  But I really wanted to go to the NHL Hall of Fame since it was only a block away and I had the chance to take my picture with Lord Stanley's cup.



I spent the afternoon finishing up my slides and I ran through the presentation to make sure the timing was right.  I was able to go through everything I wanted in 50 minutes. 

That evening was the speakers dinner.  I was looking forward to the dinner cause this would of been my first opportunity to meet Joel Spolsky.  But I this was not to be.  Why? Cause Joel forgot his passport and had to fly to NYC to pick it up.  I did however meet all the speakers and four developers from FogCreek Software.  One of which I learned was the intern (that is now working fulltime) who worked on StackExchange.com (the paid hosting version of Stack Overflow).  We spent a couple of hours geeking out telling stories.  The best story was of the assless chaps but I'll let Joey deVilla tell you that story.



So Friday came along and I was really nervous in the morning.  Joel gave his keynote and as I sat through a couple more talks I was starting to relax.  After lunch was my talk.



I've got to say Carsonified really made me comfortable before the talk.  They set up my laptop and made sure it worked on the projector system.  They even loaned me a Logitech slide switcher with a laser pointer.  This made it so that I could walk away from my laptop and walk around the stage.  I felt really comfortable after just a few minutes.  I got a couple of laughs where I was expecting laughs in my slides.  The 32" Viewsonic in the middle of the stage was great for letting me see my slides without being next to my laptop.  It really made it much easier to talk. 

In comparing this talk with my jQuery Conference talk I felt I did 200% better.  I didn't read from my slides like I did in Boston.  Everything flowed right out of me.  Now that's not to say that I did a perfect job cause there was plenty of room for improvement.



I've been monitoring the reviews on twitter and the blogs and I finding people either really got a lot out of the talk or they picked up one or two things.  I've only seen a couple of constructive criticism points for my talk.  The point is that I felt I learned a lot from my jQuery Conference talk and I applied it to this talk and I think the results really show.

After the conference I was able to take a picture with Joel Spolsky.



I also took a photo with fellow speakers Joey deVilla (right) from Microsoft and Reginald Braithwaite (left).



After the conference the speakers, Joel, some attendees and I went to a local bar C'est What? to have a drink and we had great conversations about technology.  I had the chance to talk with Joel one-on-one and got some advice on how to record podcasts, told him I'd love to hear more Israeli Army stories on the podcast and told about how I would love to know what question or answer a badge was referring to when I receive it in Stack Overflow.

I had an amazing time in Toronto and meet some great developers.

Saturday, October 24, 2009

Stack Overflow DevDays Toronto - My Slides

Here are my slides from Stack Overflow DevDays in Toronto.


Please rate my talk at Speaker Rate

Wednesday, September 16, 2009

jQuery Conference 2009 - Summary

I recently spoke at jQuery Conference 2009 in Boston on September 12, 2009.  I gave the Beginning jQuery talk to an overflowing room of about 120 people.  The highlight of my talk was letting two high school students Jamie Gillar and John Cicolella come on stage with me and demonstrate their school project, which they built using jQuery and jQuery UI plugins.

I got some really great feedback from my talk and am using some of the more constructive feedback as a little of what not to do next time.   I think less slides and more code is the key.  I walked the audience through my code example of pulling twitter into your web page using jQuery and JSON based on a previous blog post.

You can see my slides on slideshare:

It was an exhausting week but it was the most fun I’ve had in quite some time.  The first two days, Thursday and Friday, were designated jQuery Development Days in which we held meetings to discuss many topics that involved the jQuery project.

Topics like:

  • The Plugin Respository
  • jQuery UI Project
  • The Software Freedom Conservancy
  • How to spend donations (hint: more conferences)

That was followed by two days of the conference which were jammed packed with talks and networking.  In addition to all the great jQuery team members I meet like Richard D. Worth, Brandon Aaron, Jörn Zaefferer, Scott González, Rey Bango, Karl Swedberg to name just a few, I also met some interesting people like Jonathan Snook (Squarespace), Micah Snyder (Digg), Stephen Walther (Microsoft Senior Program Manager for ASP.NET) and Steve Souder (Google) (who gave me a personal demonstration of his new tool Sprite Me before his talk Sunday morning, it looks amazing). 


Rey Bango and I


Karl Swedburg and I

I also got to hang out with some guy named John Resig. I guess he’s important or something ;-).  Seriously though, I’d like to thank John for the Conference and the hospitality he showed to the jQuery team during the time we were in Boston.

So what was announced at jQuery Conference regarding the jQuery project? 

  1. The source code for jQuery core ismoving from Subversion to Github.
  2. jQuery will soon be a part of Software Freedom Conservancy to help protect the project going forward.  This will move the copyright out from under John Resig’s name and into the Conservancy to make the jQuery project truly open source.  This will also give jQuery the benefit of a voting counsel on top decisions, no one person will hold the finances and the Conservancy will now offer free legal advice.

    The jQuery Team members sign the documents to join the Software Freedom Conservancy
  3. Announced a revamped and simplified plugin repository. This is jQuery teams number one priority and is targeted to for release by end of year. (I will personally be working on the plugin repository)
  4. jQuery 1.3.3 is close to release and already boasts overall speed improvements of 3.5 times faster, looking to land of couple more live events like blur and submit before release.
  5. jQuery is planning version 1.4 to ship a stripped down version of jQuery for mobile devices. The mobile device will only strip out the Internet Explorer specific code to make the file smaller.  It will still contain all the same functionality as the full version.
  6. jQuery team members Mike Hostetler and Jonathan Sharp have formed a company called AppendTo to provide paid support of jQuery.  This should help out Corporations who are holding off on using jQuery due to the lack of official support.
  7. jQuery Infrastructure costs will be ~$0 starting in October.  Media Temple has graciously stepped up and is offering to build the project a server cluster and is providing their CDN for the project to use.  Current infrastructure costs run about $1600/month and rising with Amazon Cloudfront.  A cost that was totally unsustainable due to the growth of jQuery.
  8. Plugin authors will soon have the ability to host their plugins on jQuery’s CDN.
  9. jQuery will soon help organize and sponsor basic funding for local jQuery Meetups/Groups around the world. 
  10. The jQuery Conference will now be held four times next year in Boston, London, San Francisco and Online.
  11. Support that jQuery currently offers on Google Groups in the group jQuery-en will soon be transitioning to a forum site that will be set up.  Software is currently being evaluated to meet the needs of supporting users effectively and efficiently.

*Photos by Jörn Zaefferer


Tuesday, June 16, 2009

Selecting the fastest selector for jQuery using Firebug Profile

Today I needed to select all the h3's within a div and set a margin-top property on all items in the returned set except the first.

I came up with a few ways to return the results I was looking for (here are some jQuery examples):

$("#div h3").slice(1);

$("#div h3:not(:first)");

$("#div h3:gt(0)");

I've been reading a lot about how your selection can be optimized based on how you structure your query. So I ran each query through Firebug Profile to see which selector query was the fastest. Load the page, click on the "Profile" button at the top, run your query in the console, click the "Profile" button again to stop the profile.  You'll get the time it took to execute that statement.  Here are the results for each:

$("#div h3").slice(1); 3.305ms

$("#div h3:not(:first)"); 0.705ms

$("#div h3:gt(0)"); 2.347ms

It's clear from my testing that the second query is 2-3 times faster then the rest for my page and my specific uses.  Your specific profile times may vary based on HTML structure and selector query. So it's always good practice to test the speed of your selector if there is more then one way to get your results so that you are using the most efficient selector for your situation. 

Thursday, April 09, 2009

Is jQuery safe?

A post on the jQuery-English Google Group this morning asked is jQuery safe, was it infected with a virus?  This seemed like an odd question.  I brought it up with the jQuery team and Rey Bango, part of the jQuery Evangelism team , offered some sound advice for making sure that jQuery is safe for you to use.

1) Virus Scanner Reported Something: In some instances, anti-virus programs have reported a false positive on packed versions of various libraries in jQuery. It's definitely a false positive and not a virus in any way.

2) The jQuery downloads are basically text files that we manage & the project has been active for 3 years now. We have a tremendous number of large scale users leveraging jQuery so you can rest assured you're in good company. You can see a list of them here:

http://docs.jquery.com/Sites_Using_jQuery

One way to ensure that jQuery is safe is to download the library from a trusted source like the jquery.com servers.  But if that's not enough level of trust you can also download/link to the library from Googles AJAX Libraries API's site where Google hosts jQuery, jQuery UI, prototype, mootools and others.  Google independently inspects each release before releasing it to it's users. 

Rey continues with official places to download jQuery:


Please only download jQuery from the official site or use the version hosted on Google's CDN. Here are the official site links:

http://jquery.com/
http://code.google.com/p/jqueryjs/
http://jqueryui.com/ (for the jQuery UI library)
http://code.google.com/apis/ajaxlibs/

Downloading jQuery from any site other than the ones listed above is not recommended as we can't guarantee the validity of the code.

I hope this post will confirm to those questioning if jQuery is safe to use that it is indeed safe for use and how to ensure your experience is enjoyable.

Update: Rey posted a similar blog post on his site as well.

Friday, March 06, 2009

Promotional Video of BarCamp Buffalo

And I am in it.  Video was done by WNYMedia and was very well done.


Tuesday, March 03, 2009

My BarCamp Buffalo Slides - Intro to jQuery



Update:

Video of my presentation. 


My BarCamp Buffalo Presentation - Intro to jQuery from Ralph Whitbeck on Vimeo.

Presentation to BarCamp Buffalo on 3/3/09. My slides can be found http://ralphwhitbeck.com/2009/03/03/MyBarCampBuffaloSlidesIntroToJQuery.aspx

Wednesday, February 18, 2009

CPU statistics on yesterday's post

I got a little help promoting yesterday's blog post from the jQuery team.  I knew that a wave of users was coming so I let my host provider know and they gave me an extra CPU for the morning (VMWare rules).  They also sent over the CPU graph for the day.  I found it interesting.

The first spike was when John Resig posted a link on twitter for me. The second biggest spike was when Rey Bango retweeted John's tweet.

Tuesday, February 17, 2009

The jQuery Plugin Repository - How can it be improved?



A jQuery plugin site redesign is in the early stages of being worked on.  Now is the time to have your voice heard as a jQuery user or a plugin author.

Please leave me a comment below or send me an e-mail with what you'd like to see in a new plugin repository.  Let me know what you think works now, what doesn't work, perhaps examples of plugin sites that might be a good foundation for jQuery to build off of (i.e. Mozilla Add-ons).

All your comments will be evaluated and added to a planning document that the jQuery team will use. 

A big thank you to the jQuery community for your help.

Thursday, February 12, 2009

Where to find help for your jQuery questions?

One of the most common questions I see on twitter from people is "I need help with jQuery, any experts around?"

While this is definitely a fair use of twitter.  Being an "expert" in jQuery I don't want to reply back with "Yes, I can help" without knowing what I am getting involved in.

But not to fear there are plenty of places one can go to get help online.


My favorite place to get help is Stack Overflow (http://stackoverflow.com). Stack Overflow is the Yahoo Answers, Experts Exchange for programmers.  And the great thing for jQuery programmers is that there are a ton of jQuery experts hanging out there.  jQuery questions seem to get answered almost immediately.



For more official help try the jQuery Group on Google Groups (http://groups.google.com/group/jquery-en?hl=en).  This is a great place to get help as most of the plugin authors and jQuery core programmers are hanging out in here to help.


IRC Channels

If you require more one-on-one help you can jump in to the jQuery IRC room where at any given time there are 400+ jQuery developers hanging out and talking jQuery.  Use the following information to connect to the channel.

For general discussion and jQuery development, please visit:

Server: irc.freenode.net
Room: #jquery

For jQuery UI discussion, please visit:

Server: irc.freenode.net
Room: #jquery-ui


Good luck!


Tuesday, February 03, 2009

In case you Missed it: #jQuery Twitter posts

My #jQuery related twitter posts for the week of January 27th - February 2nd:

Friday, January 30, 2009

Selecting a ASP.NET Generated ID with jQuery

I was looking at some of the questions on Stack Overflow this evening and I came across one that had a great tip for selecting a tag whose ID was generated by ASP.NET.  So say you have a label control on your page:
<asp:label id="label1" runat="server"></asp>

The generated output of the html and the ID of that control might look like this:

<span id="ctl00_ContentPlaceHolder1_Label1"></span>

Unfortunately the generated ID of ct100_ContentPlaceHolder1_Label1 isn't always going to be the same from build to build.  So trying to select it like this:

$("#ct100_ContentPlaceHolder1_Label1").hide();
will eventually break and it won't hide the label control.

The trick is to use ASP.NET inside the jQuery selector. Label1.ClientID will return the generated ID everytime. We combine ASP.NET and jQuery into one line like this:
$("#<%= Label1.ClientID %>").hide();

This will get the generated ID of the Label control everytime.



Thursday, January 29, 2009

Building a jQuery-Powered Tag-Cloud with an ASP.NET MVC backend

NETTUTS had a great tutorial by Dan Wellman called "Building a jQuery-Powered Tag-Cloud" The problem for me was that the tutorial showed you how to connect to the database and pull tags and frequencies via PHP.

Because I am currently learning ASP.NET MVC I thought I would try to duplicate the results of the tutorial but with using ASP.NET MVC RC instread of PHP.  Here is how I did it.

I started by creating a Home Controller class.

HomeController.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Mvc;
   6:  using System.Web.Mvc.Ajax;
   7:   
   8:  namespace MvcApplication5.Controllers
   9:  {
  10:      public class HomeController : Controller
  11:      {
  12:          //
  13:          // GET: /Home/
  14:          public ActionResult TagCloud()
  15:          {
  16:              return View();
  17:          }
  18:   
  19:          public JsonResult JSON()
  20:          {
  21:              List<object> tagcloud = new List<object>
  22:              {
  23:                      new { tag = "jQuery", freq = "10" },
  24:                      new { tag = "asp.net", freq = "3"},
  25:                      new { tag = "programming", freq = "183"},
  26:                      new { tag = "code", freq = "34" },
  27:                      new { tag = "HTML", freq = "58"},
  28:                      new { tag = "javascript", freq = "23"},
  29:                      new { tag = "people", freq = "43" },
  30:                      new { tag = "Google", freq = "3"},
  31:                      new { tag = "Microsoft", freq = "1"},
  32:                      new { tag = "Apple", freq = "10" },
  33:                      new { tag = "iPhone", freq = "38"},
  34:                      new { tag = "MVC", freq = "1"}
  35:              };
  36:              return Json(tagcloud); 
  37:          }
  38:   
  39:      }
  40:  }

What's happening here is that we are making a action for the View we will create and I am calling it TagCloud.  This action isn't going to provide us any data so it's a stub action.  The next Action we create is to provide TagCloud the JSON data.  In here I am creating a static List to send back serialized as JSON.  You could also tie it to a model and use Linq to SQL to build the List.

Our URL for the .getJSON method will be: /Home/JSON

This will return JSON data that looks like this:



Notice the difference in the JSON I am bringing back and the one Dan was bringing back.  I don't have a tags: with the rest of the data nested under it.  We'll need to update a line in the jQuery to make this work now.

Let's create the View for TagCloud.


TagCloud.aspx

   1:  <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
   2:   
   3:      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
   4:      <html>  
   5:        <head>  
   6:          <link rel="stylesheet" type="text/css" href="/content/tagcloud.css" />  
   7:          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
   8:          <title>jQuery Tag Cloud</title>  
   9:        </head>  
  10:       <body>  
  11:         <div id="tagCloud">  
  12:           <h2>Tag Cloud</h2>  
  13:         </div>  
  14:         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>  
  15:         <script type="text/javascript">
  16:             $(function() {
  17:                 //get tag feed  
  18:                 $.getJSON("/Home/JSON",null, function(data) {
  19:                     //create list for tag links  
  20:                     $("<ul>").attr("id", "tagList").appendTo("#tagCloud");
  21:   
  22:                     //create tags  
  23:                     $.each(data, function(i, val) {
  24:   
  25:                         //create item  
  26:                         var li = $("<li>");
  27:   
  28:                         //create link  
  29:                         $("<a>").text(val.tag).attr({ title: "See all pages tagged with " + val.tag, href: "http://localhost/tags/" + val.tag + ".html" }).appendTo(li);
  30:   
  31:                         //add to list
  32:                         li.appendTo("#tagList");
  33:                         //set tag size  
  34:                         li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em" : (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");  
  35:            
  36:                     });
  37:                 });
  38:             });  
  39:         </script>  
  40:       </body>  
  41:    </html>  

As we start to loop through the JSON data Dan was telling jQuery to start inside tags with data.tags, since we don't have tags we can just use the variable data like so: $.each(data, function(i, val) {

The rest of setting this up is the same as NETTUTS article.  All that remains is the css.




Download the Source

jQuery-TagCloud_source.zip (44.82 KB)



Tuesday, January 27, 2009

In case you missed it: #jQuery Twitter posts

My #jQuery related twitter posts for the week of January 20th - January 26th:

Friday, January 23, 2009

jQuery vs Prototype and jQuery.noConflict()

While helping people out on twitter with jQuery lately I've found one of the most common asked questions is, "why won't jQuery work when I include prototype as well?" Well the answer to the why is simple.  jQuery and prototype are both competing for how $() is going to be used.

I set out to understand how this would break and how to call jQuery.noConflict(); and make both work.

noConflict_test.html (2.41 KB)

If you look at my code you'll see that I was having a hard time just trying to get a single line of prototype to work as it should.  I tried to display a div that was hidden with css.  A very simple task in jQuery.  Unfortunately, it states right on the Element.show documentation page that prototype is not capable of displaying elements that are hidden with css. 

Next I tried to color the text of the other element on the page.  Which to my bad luck I was injecting into the DOM and I was finding that this is impossible to do in both jQuery and Prototype.

In the end all I wanted to do was fire one prototype command and have it update the DOM in some way.  Needless to say this gave me a bad taste in my mouth for prototype.

Tuesday, January 20, 2009

In Case you Missed it: #jQuery Twitter posts

My #jQuery related twitter posts for the week of January 13th - January 19th:

Follow me to see what I'll twitter next about jQuery.

Monday, July 14, 2008

Adding link separators to a unordered list using jQuery

I figured out how to easily add a separator to a inline displayed unordered list of links using jQuery and so I'd thought I share.

So for a list like so:



I wanted it to display like this:

Ralph Whitbeck | jQuery | BrandEnsemble

Notice that the separator (|) is only between the links and not at either the beginning or end.  I should also note that when I was rendering the list it was coming from a dynamic source so I didn't have a set list to work from.

I wrote this jQuery:

$(document).ready(function(){
   $(".subnavigation li:lt(" + ($(".subnavigation li").length - 1) + ")").append(" | ");
});


So basically I used the :lt(index) selector to match against all the matches that were less then the index value.  I do that by figuring out the length of how many are selected and subtracting one.  Then finally I append my selector to all of my matches.


Update: John Resig (creator of jQuery) chimes in with an easier way to do the same thing in the comments.

$(document).ready(function(){
   $(".subnavigation li:not(:last-child)").append(" | ");
});

This works by selecting all the li's except the last child (or the last li) in the container. This will work with multiple containers on a page if there are more then one.  Thanks John for the tip.

Blog Posts by:

The Official jQuery Podcast

with Ralph Whitbeck & Rey Bango

You can subscribe to the show in iTunes or via the raw RSS feed

My Twitter Updates

View Twitter Page