jQuery Twitter API plugin

UPDATE: Plugin has been updated! For more up to date information read this post.

You might have noticed that I am talking and spending more time on Twitter lately. I have been helping Twitter users with their jQuery related questions and problems as well. If you are using Twitter and have some kind of jQuery related question I will be happy to help.

Anyway, after I found a Twitter JSON(P) API url last week, I spent some time playing with it and ended up with a jQuery plugin that when given a Twitter username retrieves and returns javascript object with user detials such as followers & following counts, full name, homepage URL, etc.

Download jQuery Twitter API - jTwitter here.
Update: Now plugin also get any number of any user's posts.

Here is an example of returned JavaScript object:

// Starting from version 1.1 plugin gets user posts
// the returned object has changed. See update.
	"name":"jQuery HowTo",
	"description":"jQuery and javascript howtos, tutorials, hacks, tips and performanace tests. Ask your jQuery questions here...",
	"time_zone":"Central Time (US & Canada)",
	"created_at":"Thu Mar 26 14:58:19 +0000 2009",

As you can see the jQuery Twitter API plugin returns Twitter user's avatar URL as well. Using this jQuery plugin you could create another plugin that would return Twitter user's avatar image.

You can see example usage and demo here.

Here is how to use jTwitter:

// I am query data for "jqueryHowto" user
$.jTwitter('jqueryHowto', function(userdata){
  //Callback functn with the user data as shown above
  $('#profile input.url').val(userdata.url);
  $('#profile #avatar').html('<img src="'
       + userdata.profile_image_url + '" />');

The first parameter is a Twitter username and the second is a callback function that will be called after jQuery gets user details from the Twitter servers.

Lock user interface plugin – uiLock

I was asked to create a user interface locker using jQuery. The main idea behind was to lock all user interactions with the website while jQuery AJAX loads block contents and unlock when content is loaded. So I thought I would share the code and released it as a jQuery plugin called uiLock.

The plugin extends jQuery and adds two main functions called $.uiLock(); and $.uiUnlock();

Here is how to use uiLock jQuery plugin:

// To lock user interface

// To unlock user interface

$.uiLock(); takes an HTML text argument that will be placed in the page overlay. You can style the overlaying layer using CSS. You can change font color, background color, etc. To style uiLocker use #uiLockId CSS selector.

For example:

  background-color:red !important;

The plugin demo can be found in the plugin archive. Here is a screenshot of the plugin at work:

uiLock jQuery plugin screenshot

User will not be allowed to interact with the website on the screenshot above. Basically, we are blocking all user actions with an extra layer that uiLock jQuery plugin adds.

Download uiLock jQuery plugin here.


It is Friday and we don’t want to read long posts and tutorials. So today’s post is going to be short and sweet. I’ve been playing a lot with Twitter lately. I wrote some jQuery and javascript functions that get user details, etc. I will share it with you next week.

But for today, I would like to share Twitter’s JSON and JSONP API URL. I am sharing it because it was hard to find it first. I actually wrote a jQuery plugin that gets Twitter user details using my previous post on cross site AJAX querying method. All Twitter API usage tutorials and articles I found on internet were based on RESTful non JSONP API, so I though I'll share Twitter JSON(P) API with you. Anyway...

Twitter JSON(P) API URL:


Here is a code to use with jQuery’s $.getJSON() function:


We have put ? (question mark) for callback function name so jQuery could replace it with a dynamic one that it has created.

Update: Check out jQuery Twitter API plugin – jTwitter, that uses this Twitter API.

AJAX update content every X seconds

I was asked several times on Twitter how to update some web page section or a block content on a page every x seconds. Some real life examples of this functionality are Twitter search results that come out when there are new tweets with search keyword or bit.ly real time link tracking that updates it’s charts every 5 seconds.

It is clear without saying that we are going to update our page content using AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is JavaScript's built-in setInterval() function. It lets you to run some javascript function every X seconds. For example, the following code would pop alert box every five seconds:

setInterval( "alert('Hello')", 5000 );

Now consider we want to update shouts in our shoutbox every 10 seconds.

function updateShouts(){
    // Assuming we have #shoutbox
setInterval( "updateShouts()", 10000 );

The code above will run every 10 seconds (10,000 ms) and update the contents of #shotbox with new shouts.

Get geographical location (geolocation) by IP address using jQuery

Today I came across this post called “IP Address Geolocation Javascript API : JSON”. The author provides you with a free geolocation query URL. The API returns the geographical location of the queried IP address with some additional information such as:

	'IP': '',
	'CountryCode': 'US',
	'CountryName': 'United States',
	'RegionName': 'California',
	'ZipPostalCode': '94043',
	'City': 'Mountain View',
	'Latitude': '37.4192',
	'Longitude': '-122.057'

// In case of an error
	'status':'parent server not responding'

Update: the URL has been changed!

The JSON geolocation querying API’s address is:


The URL above is dead, instead use this one:

And the great thing is, you can identify your website visitor’s IP and Geo location by simply querying the API without any parameters like this:


Knowing your users’ IP and/or location, you might add a behavior to your website that is specific to some location. For example, offering some advertising to US only visitors, or popup with special offer to European users.

Anyway, here is a sample jQuery code to query the API:

// Build the URL to query
var url = "http://iplocationtools.com/ip_query.php?output=json&callback=?&ip=";

// Utilize the JSONP API
$.getJSON(url, function(data){
    if(data['status'] == 'ok'){
        // Do something with the data
        $('#profile #ip')
        $('#profile #country')

Here we are not specifying any IP address in the url variable that is why it is getting current user’s data.

Shorten long URLs with jQuery & bit.ly service

I recently signed up to twitter and actively engaging with people who are interested in jQuery. Twitter is a great service and there are all kinds of developers who are sharing interesting links and resources. So it is some kind of interest news group for me. Since you can only have 140 characters in your post, sharing long links limits you. URL shortening services to the rescue. There are lots of free URL shortening services, some are just for long URL shortening, some provide more features like real time click tracking, geostatistics and private URLs.

The great thing about them is that they also provide you with an API. So I thought that there is a way we can make a use of them in our jQuery code. One of the most popular services is bit.ly. You can read more about its API here.

I wrote a simple jQuery code that utilizes the service.

Here is an example:

  // set up default options
  var defaults = {
    version:	'2.0.1',
    login:	'bitlyapidemo',
    apiKey:	'R_0da49e0a9118ff35f52f629d2d71bf07',
    history:	'0',
    longUrl:	''

  // Build the URL to query
  var daurl = "http://api.bit.ly/shorten?"

    // Utilize the bit.ly API
    $.getJSON(daurl, function(data){

        // Make a good use of short URL


This code does not do much, but I hope you will find a good use of it in your own applications.

jQuery image swap or How to replace an image with another one using jQuery

Swapping one image with another is probably one of the most used javascript techniques. Also Dreamweaver made “image replacement” even easier for non HTML/Javascript programmers by including this feature out of the box. One thing about Dreamweaver’s image swapping javascript is that it’s not the most beautiful javascript code. Well, as always with anything javascript related, jQuery is to the rescue.

jQuery makes dynamic image swapping a peace of cake. All you need to do to replace your image with another one is to replace its src attribute. The browser will take care of the rest.

Here is an example:

$("#myImage").attr("src", "path/to/newImage.jpg");

In the code above we are:

  1. Selecting an image to be replaced;
  2. Changing its src attribute to the new replacer image’s URL.

To avoid page jumping and improve user experience it is a good idea to preload your images before you swap them.

Select text in input box on user select or focus

A colleague of mine who is not very javascript (or for that matter jQuery aware) asked me to help him to do a little trick with jQuery. He needed to select the contents of the input box when user selects it (basically, when user focuses in the input field).

In case you're Googler looking for a way of getting input field's value, see the code snippet at the end of the post.

Selecting inputbox text on focus is easy and it's 3 lines of jQuery code. But it adds nice usability touch to your website. This "select all" behavior is browser default when you browse through form fields using TAB key, but when you click on the input text field it does not behave like that.

Here is jQuery code to select text inside an input field on user click or focus.

    // Select input field contents

select() is a built in javascript method. It selects content of the field it is called on (in our case, an input field).

We can add this behaviour to all text input fields on the page by extending the jQuery selector.

// Add this behavior to all text input fields

Let's change the selector in the example above event more to add this behavior to all password and textarea fields as well.

// Add this behavior to all text input fields
$("input[type=text], input[type=password], textarea").focus(function(){

Also, we can improve our form usability by only selecting the contents of text fields, if their value have not been changed from their default values.

$("input[type=text], textarea").focus(function(){
    // Check for the change from default value
    if(this.value == this.defaultValue){

The code above selects all text content of textarea if and only if it's value has changed from its' default value.

Just in case, you came here from search engines looking for a way to get input or textarea's contents, here is how to do it.

// Select the input field & call .val() method

// For textarea, you need to call .html() method instead

How to make jQuery / Prototype / MooTools & others play nicely with Smarty

Smarty is the first template engine I have learned and used in my projects. Smarty makes your PHP code cleaner and promotes the V in MVC. Here is an example of Smarty template:

    User Information:<br />
    Name: {$name}

Smarty will replace the {$name} with the variable that you set in your PHP code. Anyway, do you see the problem that might arise when you try to embed your jQuery code or any other javascript library (like Prototype, MooTools, Extjs, etc.) that uses $ as a function name in the <head>?

Smarty parses the file and whenever it encounters the {$ it would try to parse it and replace with the PHP variable like in this example here:

<script type="text/javascript">
        $(".clazz").css("color", "red");
    User Information:<br />
    Name: {$name}

The problem:

Smarty would not care that { and $ are on different lines and would see it like {$(".clazz.... The code above would cause this Smarty error:

Fatal error: Smarty error: [in templateFile.tpl line 5]: syntax error: unrecognized tag: $(".clazz").css("color", "red"); (Smarty_Compiler.class.php, line 455) in C:\PHP\smarty\libs\Smarty.class.php on line 1092

The solution:

There are couple of things you can do about this problem:

  1. Move your javascript (jQuery, Prototype, etc.) code into the external .js file.
  2. Use jQuery() instead of $().
  3. Use Smarty’s {literal}...{/literal} directives to tell Smarty parsing engine that it should not interpret the code within the block.


Here is how we can rewrite our javascript code above using the 3rd tip:

<script type="text/javascript">
        $(".clazz").css("color", "red");
    User Information:<br />
    Name: {$name}

Display loading GIF image while loading through AJAX

Well, let's face it, AJAX is everywhere. Nowadays clients want AJAX "enabled" web applications. They want their web sites to be Web2.0 and that is usually associated with using AJAX. No doubt using AJAX to load parts of your page and use more javascript effects, made easy by jQuery, is a great way to bring your website to life. But we should not forget about our users and the website usability. That is why it is a good practice to display something like text or image that informs users that the content is being loaded or processed.

Now, let's see how can we display a loading image while requested content is being loaded by one of the jQuery's AJAX functions. Here is what happens:

  1. Something triggers AJAX request (like "search" button click);
  2. We put the loading image or a text that ask for user patience to the place where we would later insert the loaded content (or anywhere else);
  3. After remote content is fully loaded, we remove/hide the loading image/text and insert the loaded content.

To make it more apparent, imagine we have HTML page with this markup:

<button id="btnLoad">Load Content</button>
<div id="content">
  Please click "Load Content" button to load content.

We want to load content when a user clicks on the "Load Content" button. So we need to bind a click event to that button first and make AJAX request only after it is fired.

    // Make AJAX call

The above code loads contents from http://example.com into the <div id="content">. While the page is being loaded we want to display our animated GIF image in the "content". So we could further improve our code like so:


  // Put an animated GIF image insight of content
  $("#content").empty().html('<img src="loading.gif" />');

  // Make AJAX call

The .load() function would replace our loading image indicator with the loaded content.

Final note:

You might be using jQuery’s other AJAX functions like $.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.

If you have any question, please tweet me.

Problems with jQuery mouseover / mouseout events

Today I have a quick note for you that will probably save you time someday. Basically it’s a workaround for a bug when you have parent element with children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.

The problem:

When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.

The solution:

The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.

The reason:

This solution works because mouseover and mouseout events do not bubble from child to parent element.

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem

Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.

The solution:

// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
    // Minimized code, suggested by Kovacs
    $('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);