Archive for the 'JavaScript' Category

416th Wordpress Twitter Plugin

Today my Recently on Twitter wordpress plugin became the 416th plugin to join the wordpress Twitter plugin directory. I’ve been told that the 415th previous attempts didn’t load asynchronously or otherwise caused the page to stall during render. Hopefully, this one does a slightly better job, though I haven’t actually investigated the competition. This plugin took about 30 minutes to develop, mostly because I have created around 10 different iterations of the same concept for previous clients and employers.

Let me know if you find it useful. You can find details on usage and installation here. Some of the features include:

  • Loads Twitter data asynchronously after the DOM ready event
  • Automatically links Urls
  • Automatically links Twitter Usernames
  • Automatically links hash tags
  • Always fresh data, even with WP-cache & Super Cache
  • Works with both Widget enabled and regular wordpress themes

You can see it in action at the bottom of the ride side of this blog. Enjoy!

jQuery Array Chunk plugin

Since I am working almost exclusively in jQuery, I am much more inclined to convert common utilities I have written to jQuery plugins, my latest is the JavaScript array chunk method.

You can see the complete code and a usage example below, or download the plugin via the jQuery plugin library.

Usage is as follows:

 
        (function($) {
 
        	$.chunk = function( array, chunkSize ) {
        	   var base = [], i, size = chunkSize || 5;
        	   for(i=0; i<array.length; i+=chunkSize ) { base.push( array.slice( i, i+chunkSize ) ); }	
        	   return base;
        	}
 
        })(jQuery);
 
        var myArray=["apple", "onion", "orange", "potato", "pear", "grape", "tomato"], myChunkedArray=[];
        myChunkedArray = $.chunk( myArray, 3);
        console.log( myChunkedArray )
 
        /*
            Output:
 
            myChunkedArray = [
                ["apple", "onion", "orange"],
                ["potato", "pear", "grape"],
                ["tomato"]
            ]
        */

jQuery Time Format Plugin

When it comes to real-time, there is nothing that says it like a cool time date display. That’s why I am releasing my jQuery.timeFormat() plugin. It’s extremely simple, it takes a timestamp from the server in seconds and calculates the difference. The return response is of the format:

  • Now
  • 2 mins ago
  • 5 hours ago
  • 1 day ago
  • January 15

This is the same logic I use in my last.fm wordpress plugin. The code is below or available via the jQuery site.

/*
    name : timeFormat
    file : jquery.timeFormat.js
    author : gregory tomlinson
    Dual licensed under the MIT and GPL licenses.
    ///////////////////////////
    ///////////////////////////        
    dependencies : jQuery 1.4.2
    ///////////////////////////
    ///////////////////////////
 
*/
 
(function($) {
 
    /*
        Format the time by:
            1. taking existing timestamp from server
            2. calculate current time
            3. find difference
            4. Display:
                    Now
                    2 mins ago
                    3 hours ago
                    1 day ago
                    January 15
    */
 
    $.timeFormat = function( timestamp ) {
        var time = handleDate( timestamp );
        return time;
    } 
    function handleDate( timestamp ) {
        var n=new Date(), t, ago = " ";
        if( timestamp ) {
          t =   Math.round( (n.getTime()/1000 - timestamp)/60 );
          ago += handleSinceDateEndings( t, timestamp );
        } else {
            ago += "";
        }
        return ago;
    }    
    function handleSinceDateEndings( t, original_timestamp ) {
        var ago = " ", date;
        if( t <= 1 ) {
            ago += "Now";
        } else if( t<60) {
            ago += t + " mins ago";
        } else if( t>= 60 && t<= 120) {
            ago += Math.floor( t / 60 ) + " hour ago"
        } else if( t<1440 ) {
            //console.log(t)
            ago += Math.floor( t / 60 )  + " hours ago";
        } else if( t< 2880) {
            ago +=  "1 day ago";
        } else if( t > 2880  && t < 4320 ) {
            ago +=  "2 days ago";
        } else {
            date = new Date( parseInt( original_timestamp )*1000 ) 
            ago += months[ date.getMonth() ] + " " + date.getDate();
        }
        return ago;
    }
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
})(jQuery);

bit.ly Bookmarklet API Hack

I recently started using bit.ly for storing my bookmarks instead of delicious. While bit.ly isn’t entirely ready to be a bookmarking service for everyone, it does have some cool features, such as a public history, and saves me a hop for sites that I want to bookmark plus need a short URL in order to tweet.

In order to facilitate my new, higher volume, usage of bit.ly, I wrote a little bookmarklet hack that throws the current page into bit.ly and alerts back the shortened URL in case I need it.

I put together this form that will let anyone take advantage of the hack. You’ll just need to input your user name and bit.ly API key. Then you never have to worry about logging in again. Enjoy.

jQuery Plugins Architecture, An initial overview

I have been dabbling in different styles of jQuery plugin architecture for a few months now. At first, I tried to find a definitive style to emulate, but the jQuery docs don’t express much more than how to leverage the basic API for plugins. The conflict I was having about approach is jQuery is a DOM-centric library, however, not all plugins solely manipulate the DOM. Choosing the best pattern has been a struggle. Below I outline some of the pros and cons of three different formats. I have been using the last pattern for the last few weeks and currently prefer it.

At the office, I began using the below basic skeleton.

//<![CDATA[
 
/*
	name : pluginname
	file : jquery.pluginname.js
	author : gregory tomlinson
	(c) Copyright 2009 AOL LLC
	///////////////////////////
	///////////////////////////		
	dependencies : jQuery 1.3.2
	///////////////////////////
	///////////////////////////
 
*/
 
(function($) {
 
	$.fn.pluginname = function( options ) {
 
		var defaults = {
		    // declare all plugin defaults here
		};			
		var ClassName = {
 
			options : {},
			ui : {
				bx : null
			},
			init : function( obj, options ) {
				this.options = options;
				this.ui.bx = obj;
			}
 
		}, class_options = $.extend(true, defaults, options),
		   j_obj = $(this);
 
		ClassName.init( j_obj, class_options );
		return j_obj;
	}
 
})(jQuery);
 
//]]>

This approach definitely has its strengths. Coming from a background of developing MooTools classes in the past, it was very familiar to me. What I liked about it is it allows me to instantiate multiple instances of the plugin without collision and control the scope very easily.

As you can see, I cache the original value of this into my ui object. This allows me to retain access to the element or group of elements that are originally targeted via jQuery('<element>'); It also let me adjust the scope of the ‘this’ keyword to target my specific internal methods.

One of the nicest things about this approach is all the methods are private. But, it means you cannot call any additional methods, or maintain control over anything in the plugin once it’s been originally initialized. While they are definitely scenarios where having private methods is a huge plus, it’s not a one sized fits all solution.

Additionally, because I changed the scope of the this keyword, it’s difficult for other developers, familiar with jQuery, to quickly read and understand my pattern and code. One major downside is you junk up the code with tons of references to this.

This led me to begin thinking about alternatives to the above approach. I am currently trying out a new format with the FriendFeed plugin that I recently released. Here is the bare bones of that approach.

//<![CDATA[
 
/*
	name : friendfeed
	file : jquery.friendfeed.js
	author : gregory tomlinson
	site: http://gregorytomlinson.com/
	///////////////////////////
	///////////////////////////		
	dependencies : jQuery 1.3.2
	///////////////////////////
	///////////////////////////
 
*/
 
(function($) {
 
	$.fn.friendfeed = function( user, options ) {
 
		/* declare INSTANCE specific variables and settings */
		/* extend the defaults to include all user specified options */
		var defaults = $.extend( true, $.friendfeed.defaults, options );	
 
		/* do anything I want here, keep a cached version of the override options for this instance. */
 
		return this; /* jQuery default behavior, return container */
	};
 
	$.friendfeed = {
 
		log : function( str ) {
			if( !this.defaults.debug ) { return; }
			try {
				console.log( str );
			} catch(e){}
		}
	}
 
	/* define defaults for override */
	$.friendfeed.defaults = {
		/* this is publicly accessible */
	};
 
})(jQuery);

Again, this approach has several strengths. Because I have moved the specific method I might need, in this case ‘log’ outside of the $.fn.method, I can retain access to it, aka it’s public, not private. The biggest drawback to this approach is that collision could occur. Also, options that may be specific to this instance aren’t always easily accessible internally, which can lead to default values that were intended to be overriden at runtime containing incorrect values.

The final pattern I have playing with most recently has mostly private methods, but the pattern doesn’t alter the scope of this, and the code isn’t junked up with tons of references to this

Here is a sample skeleton of the pattern

//<![CDATA[
 
/*
	name : pluginName
	file : jquery.pluginName.js
	author : gregory tomlinson
	site: http://gregorytomlinson.com/
	///////////////////////////
	///////////////////////////		
	dependencies : jQuery 1.3.2
	///////////////////////////
	///////////////////////////
*/
(function($) {
 
	var defaults = {
		/* stuff I want to override  */
	}, el;
 
	function myMethod() {
		// do private method stuff
	}
 
	function eventMethod(e)  {
		/* listen to my element */
	}
 
	$.fn.pluginName = function( options ) {
		// do stuff with the method here
		el = this;
		$.extend( true, defaults, options );
		el.bind( 'click', eventMethod ); // attach an event for kicks
		myMethod();
		el.trigger('myPluginName');
 
		// standard jQuery - return the jQuery Object
		return this;
	}
 
})(jQuery);

It’s very simple to read and the code is fairly concise. It has some limitations, like the inability to directly alter the code once it’s been initialized, however, you can easily attach listeners that can handle that action for you.

I’m not particularly fond of any of these approaches, though I have found myself using the last pattern more often recently. There is definitely something to be said for the MooTools class pattern, though I do find it irritating that MooTools attempts to turn JavaScript into a classical language. jQuery doesn’t mask JavaScript’s prototypical nature and I find that more honest. I plan to keep exploring approaches and find a pattern that both fits my style and leverages the strengths of jQuery.

Know the Language, Now what?

Last week, I posted on knowing the language, in the context of it being a personal struggle. Since posting, I have had several conversations about the subject as well as receiving the first comments in quite some time.

I want to expand on my personal struggle of knowing the language. My focus continues to be jQuery, which is technically an API, but it has an explicit style and feels more like a language than an API.

I have been trolling the jQuery bug tracker for the past several days. It’s my personal goal to contribute to the jQuery core by the end of this year, which is ambitious to say the least. To me, the best method seems like reading bugs and trying to understand what’s going wrong inside the library. I am becoming intimately familiar with both jQuery and the Firebug debugger and profiler.

I have learned some amazing things already. One that I find most fascinating is that simple confusion on the API can lead to reporting mistakes as bugs. I don’t want to pick on anyone, but one of the first bugs I investigated was an issue with jQuery.ajax();. I setup a local test and started digging into the issue of why the error event was never being called for a 404 URL.

I spent almost an hour digging into the guts of the XML HTTP Request Object, only to realize that the bug was due to human error. I learned a very valuable lesson. Start at the beginning. Don’t assume anything. The bug has since been closed based on my recommendation. That probably seems mundane, but for me it’s very exciting to be contributing to something that I use every day.

Most importantly, investigating bugs is giving me a reason to dig deep into the inner workings of the jQuery library. When using the debugger, I can follow the exact path the code follows, which is sometimes very surprising. While investigating an issue with document.write and jQuery().wrapInner, I actually spent an hour and a half stepping through the code one time. It gave me a solid appreciation of the sheer number of convenience methods jQuery contains.

If you really want to advance your personal struggle of knowing the language, the first step is spending time working with it. Reading someone’s code is an amazing way to discover patterns and techniques. Trying to patch bugs, elegantly, is a crash course in a language. If you really want to know the language, you have to take a step beyond your comfort zone and don’t be afraid to fail.

Know the language? Why bother

I’ve spent the last few months really digging into jQuery. From in-depth reads of the source code, to examining plugin patterns, all things jQuery have fascinated me lately. The more I dig into the library, the more I have realized it has the possibility of wild power and abuse, mostly because it makes JavaScript look magical.

For even seasoned JavaScript veterans, the ease at which jQuery can do the seemingly impossible is awe inspiring. With a single command, you can select elements at least 3 different ways. That may sound simple, but it’s pretty far from simple under the hood. For instance, you can select an element by Id, class or a collection of elements. The following code illustrates these points:

jQuery('#myId');
jQuery('.myClass');
jQuery('div');

How on earth can jQuery pull this off? Under the hood, jQuery works hard to make your life simple. But, that doesn’t make it fast, or a good idea. And it’s not until you check the JavaScript profiler that you realize that jQuery isn’t magic. It isn’t doing anything you can’t do. It’s just making complicated DOM selection commands easy to access.

Douglas Crockford has long argued that JavaScript is fast, but it’s the DOM [Document Object Model] that makes JavaScript slow. I agree on this point, but without the DOM, JavaScript isn’t really all that useful. Sure, the XHR (ajax) request object is cool. But if you can’t display that ajax data, what’s the point?

Understanding how JavaScript behaves in all browsers is a daunting task to say the least. But really it’s how the DOM behaves in different browsers that is the more surreal challenge. There aren’t too many different ways a for loop or an if conditional can behave. This is where libraries like jQuery, MooTools and Dojo come in. Libraries make the DOM API more consistent for application code, essentially, they make my life easier and maybe yours too.

Libraries like jQuery, which has an amazingly low learning curve, excite people about JavaScript. It makes even total beginners appear good, and also dangerous. And that’s the fun part. jQuery lets you build an application that has an impact. That’s fun to use. And, that’s fun to build.

Cranky JavaScript veterans get frustrated by libraries. People rarely take the time to learn JavaScript, let alone a library API. Why bother reading the source code when examples are a Google away. This behavior leads to scary things, like including multiple libraries on the page or writing JavaScript code that crawls the entire DOM. These are the types of things experienced veterans shake their head over. Several times over the past few months I have reviewed other people’s code and been shocked by some of the things they are doing. I have shaken my head at them. Even scowled a little, or a lot. But it wasn’t until recently that I realized that it doesn’t matter.

It doesn’t matter if you have the most amazing grasp on JavaScript and can work on Crockford’s level. It doesn’t matter if you’re the most horrible coder and make bad decisions everyday. None of that matters. You’re skill in a language is a personal struggle. The public struggle is the experiences you’re building, whether or not your jQuery application engages its users. I want to get better at coding because I enjoy it. But that’s not universal. The only universal thing we can share is the community you build around a product, whether or not you know the language doesn’t matter, why bother.

jQuery – Collection Methods and Static Methods

jQuery can cause a little confusion when you’re first working with it. Once you understand the difference (and similarity) between collection methods (known as ‘methods’ in jQuery docs) and static methods (known as ‘functions’ in the jQuery docs), all the dual use and duplicate function names suddenly become clear.

Let’s talk a little about the .data() method and how it can be accessed. As stated in the jQuery docs, you can assign data to any element via the collection method like below:

// collection .data() method
jQuery('#myId').data('myInfo', { item : 'has a value' });
// and access that data like so:
var getData = jQuery('#myId').data('myInfo');

Pretty useful. Now you can associate element specific data in the jQuery cache object for retrieval later. However, this isn’t the only way to get to this information, you can also access it (read & write) via the static method. That would look like the following:

var getStaticData = jQuery.data( jQuery('#myId').get(0), 'myInfo' );
// alternative
var getStaticData = jQuery.data( document.getElementById( 'myId' ), 'myInfo' );

The difference here is that jQuery stores the key as the actual element, not the jQuery wrapper for that element. So the following would fail.

// will fail because provides the jQuery object wrapper for this element
var getStaticData = jQuery.data( jQuery('#myId'), 'myInfo' );

Of course, you would never want to actually access the .data() method statically, because the collection method does a few things under the hood to make sure everything is working as expected. For example, when retrieving data a ‘getData’ event is triggered, as well as some basic error handling. Regardless, it illustrates an interesting difference and similarity between collection methods and static methods in jQuery.

You can take a closer look at the .data() method by downloading the jQuery 1.3.2 source and taking a look at lines 1367 for the collection method and 1274 for the static method.

jQuery – The Context Argument

jQuery has an awesome feature known as the context argument. It’s pretty lightly documented, but it’s extremely useful. Basically, it let’s you do selectors within a specific context. Let’s look at an example.

    <div id="myParentId">
        <div class="childOne">This is the first Child</div>
        <div class="childTwo">This is the Second Child</div>
        <div class="childThree">This is the Thid Child</div>
   </div>

The above is just a simple XHTML scenario.

// basic selector at the top level and cache in a variable
var pid = jQuery('#myParentId');
// select the first child in the context of the myParentId
jQuery('.childOne', pid).bind('click', function(event) { 
        /* do stuff on click to the first Child */ 
});
// select the second child in context of myParentId
jQuery('.childTwo', pid).bind('mouseover', function( event ){ 
       /* do stuff on mouse over for the  child*/ 
});

This is an overly simplistic demonstration of context, but as you can see, it’s essentially like the .find() method. Of course the above could easily be accomplished using many different methods including ‘:first‘ or ‘.eq(index)‘. However, if you are caching your jQuery objects as Dave Artz suggests in his jQuery performance rules, the context argument is super useful.

My Life Anywhere, the jQuery FriendFeed Plugin

Take your life stream anywhere on the web with my recently completed jQuery FriendFeed plugin. It’s a simple little JavaScript plugin that displays everything you pipe into FriendFeed plus comments made via FriendFeed. It’s super simple, and super useful.

The implementation is very easy. Just include jQuery 1.3.2 and the FriendFeed plugin on the page via a script tag. You can get both files on the jQuery site linked above. Then you just need to instantiate it. The entire thing might looking something like this.

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.friendfeed.js"></script>
 
<div id="activityStream"></div>
 
<script type="text/javascript">
var options = {}; // optional second parameter to override $.friendfeed.defaults values
jQuery('#activityStream').friendfeed( 'username', options );
</script>

Check out this demo I am using on my homepage. In the release on the jQuery site, I have also included some very simple CSS. The way the JavaScript is developed, you will be able to override everything. I make it simple by setting up a defaults object that can be manipulated via the second argument.

Additionally, you can replace or alter any method or value found in the $.friendfeed object by merely leveraging $.extend(); Look for more in depth documentation and usage in the near future. Or, if you want to share your samples, leave a comment below.