JavaScript Books That Should Be Required Reading

15. September 2010 10:38

I often get asked what books I recommend for developers looking to get more into JavaScript. Often they're looking for something specific to a given framework, most often jQuery. Although there are some great jQuery and a couple of jQueryUI books as well, I'd recommend the following books first and formost for those with some knowledge of JavaScript, but wanting to get a better grasp.

The first half of this year I read through eight recently published books centered around JavaScript and these are the one's I would recommend.

Book Cover--JavaScript: The Good Parts
JavaScript: The Good Parts is one of two JavaScript books that I feel should be required reading for all web developers. Even if you've jumped into JS and don't care to start with entry level re-hashes, this is a great read. I don't agree 100% with Douglas Crockford's views. However, this is a great read that will give some insightful concepts and ideas. Also worth looking at is Crockford's video series on YUI Blog.

Book Cover--Even Faster Web Sites
Even Faster Web Sites: Performance Best Practices for Web Developers is the other book I feel should be required reading for all web developers, and even designers. It covers a lot of great examples of how JavaScript and other elemental decisions in the design and markup of a site impact performance. There isn't as much specific to JS as High Performance JavaScript (Build Faster Web Application Interfaces), which is another good read. There's about a 50% overlap between the two books, and I feel that the former is a much more important read and reading both will get very redundant, very quickly. More...

Tags: ,

Browser detection script

13. September 2010 15:07

This javascript will add a global browser object, with properties to match the current browser version.

Note: it does use navigator.userAgent strings for version detection. It should be used for resolving browser UI quirks, not in place of feature testing.

You can output the detection (after it is loaded) to say a div with an id of diagnostics via:

jQuery(function($){
    var bl = $('<dl></dl>');
    for (var x in browser) {
        if (!isNaN(browser[x] || undefined)) {
            bl.append(
                $('<dt></dt>').text(x)
            ).append(
                $('<dd></dd>').text(browser[x])
            );
        }
    };
    $('#diagnostics')    .append('<br /><br />')
                        .append(bl)
                        .append('<br class="clear" /><br />');
});
More...

JavaScript T-Shirt

20. April 2010 09:44

Thinking it would be cool to put this on a T-Shirt, with the jsninja.org logo on the front, and the following code snippet on the back.

    var a = ["lawn","off","get","my"];
    var o = (function(){
        var u = function(){
                var t = this;
                var s = arguments;
                return [t[s[0]],t[s[1]],t[s[2]],t[s[3]]];
            };
        var b = Array.prototype.slice.call(arguments);
        var a = b.shift();
        return u.apply(a,b).join().replace(/\,/g,' ');
    }(a,2,1,3,0));
    alert(o[0].toUpperCase() + o.substr(1) + '!');

Packaging JavaScript

13. April 2010 10:59

I've been working on a number of web based applications recently, and have taken to using a few techniques that I thought I would share. I won't be sharing the code so much, which is ASP.Net centric, but will discuss what I am trying to accomplish.More...

Single-window state machine.

1. April 2010 15:19

I'm currently working on a project where one of the applications has a subform, or child form that has interactions that are separate from the main page within the application. The main page is essentially a filter form, with a results grid. Each item in the grid displays a child form, when the child form is completed, the original screen is displayed again.

Sounds simple enough right? Well, the business desire is to have the filter option form keep its' settings when returning to the page. My initial solution was to use a jQueryUI dialog based option (via an IFrame). Which works great, except in certain conditions IE7 flickers when the mouse moves in/out of the IFrame itself if there are scroll bars present. ugh.

I didn't want to use cookies, or server-side session state as these will affect all windows using the main form. If a user launches the app in a new window, with different filters set, I didn't want these windows to effect each other. Then it occurred to me, I could use window.name to store the state of the form when entering, and leaving the page. I tend to store an "__original_value__" for each form element when a page loads, that way its' easy enough to return to default values later on via code.  More...

JS Function arguments and optional arguments

19. February 2010 12:13

I hate to admit it, but I do read Stephen Chapman's Blog, and to be honest I tend to find a lot of the things he covers as incomplete, or outright not the best way to do something. A lot of entries are simple repeats of past entries as well. In the past I've had comments censored, specifically when he stated that you should just ignore IE in a prior post, I had a bit of a strongly worded response. In any case, today's entry covered Optional Function Arguments. There's one small point he missed the boat with here regarding the arguments instance.

"That is as far as the similarity to arrays goes though as none of the other methods and properties that can be used with arrays can be used with the arguments object."

It is possible to easily convert the arguments object to an Array instance though. Here's a simple example.

function argumentsToArray() {

  //convert object arguments to args Array
  var args = Array.prototype.slice(arguments, 0);

  //alerts true
  alert(args instanceof Array);

}


I've thought about, and may actually do more of these annotation posts. I've also been thinking about doing some compilation posts with information from Ajaxian, DailyJS and a few other sites.

Detect empty values in JavaScript

15. February 2010 11:14

Okay, this is a quick one. There are several states that can be considered empty in JavaScript, a non-numeric value in a number, an invalid date, and empty string, an undefined value, and a null value. The issue is that some of these require testing against isNaN, and others will evaluate as matching null or an empty string (ex: the number zero and the boolean false). What I wanted was a simple method to check for a non-empty object or string, here it is.

function isEmpty(obj) {
    if (typeof obj == 'undefined' || obj === null || obj === '') return true;
    if (typeof obj == 'number' && isNaN(obj)) return true;
    if (obj instanceof Date && isNaN(Number(obj))) return true;
    return false;
}


How it works, is first it tests for an 'undefined' object, an object that is explicitly equal to null, or explicitly equal to an empty string. If it matches, it's empty. From here there's some more specific checking, if it's a number type of variable, and isNaN (Not a Number), then it's empty. If it's a date, and Number(obj) (which gets the value of the date as a Number) isNaN, then it's an invalid date, and ergo isEmpty. Otherwise the isEmpty returns false (valid, non-empty value). Hope this helps some of you. :)

Classy JavaScript - Best Practices

11. February 2010 13:26

Okay, so you really want to be able to have some of your JavaScript methods to have access to a variable that is private, but maintains state between calls. The first piece of knowledge, is that you can have the contents of a function execute itself at runtime.

(function(){ /*Your actions here*/ })();

This is a very common method of defining complex classes and libraries, that can have their own variables or methods that aren't otherwise available to the object model outside this closure. When you utilize "this" within the function's closure it will be default to the global object, which in the Browser DOM is "window".

(function(){
    this.test = "Test Value";
})();
alert(test); //alerts "Test Value"

Usually when creating libraries in JavaScript it's a good idea to create namespaces for your library. More...

EcmaScript 5's Date Extensions

7. January 2010 10:44

Okay, so you want to utilize some of the niceties of the new EcmaScript 5 extensions to Date.  Namely they've added a nice instantiation from an ISO-8601-style string, as well as a Date.prototype.toISOString method definition.  In addition there are Date.UTC and Date.now methods defined.  As the nice guys over at Mozilla have offered script based extensions to Arrays to support their method extensions there, I wanted to do something similar for Date instances.  I've managed to do this, and have had it done since the ES5 specs were released, but figured I should put this out there for anyone interested.

var epoch1 = new Date("1970-01-01T00:00:00.000Z");
var epoch2 = new Date(0);

if (epoch1.getTime() == epoch2.getTime())
    alert("Epochs match!");
    
alert(epoch1.toString()); //localized date instance of the JS epoch
alert(epoch2.toISOString()); // "1970-01-01T00:00:00.000Z"
alert(epoch1 instanceof Date); // true
alert(epoch1.constructor == Date); //true
alert(Date.UTC(1970,0,1,0,0,0,0)); // 0

I also have a few convenience methods for handling Microsoft's JSON encoded strings. As well as rolling a date from a "Local" or "UTC" version.

DateExtensions.js (11.67 kb)

Edit 2010-01-08: I added missing support for .constructor == Date

Getting the Server-Side Offset to the JavaScript Epoch in C#

3. September 2009 16:50

Just in case anyone else needs it, here's my method for getting the millisecond offset of a server's local time to UTC time in milliseconds, for use in client-side JavaScript.

private int ServerSideJsUtcOffset
{
    get {
        DateTime epoch = new DateTime(1970,1,1);
        int offset = (int)epoch.ToUniversalTime().Subtract(epoch).TotalMilliseconds;
        return offset;
    }
}

There's really not much to it, it's mainly so that I can handle converting serialized dates to a proper local time on the client. The DateTime objects in question are stored in a database as the UTC date-time, via an ORM tool, and sent to the client with System.Web.Script.Serialization.JavaScriptSerializer. All the server-side code uses the same ORM tool, and all the client-side JSON is processed via the same local parser. So it was simply easier adjusting the client-side parser than it was to adjust the server-side class hierarchy.

I should note that I could have set the initial date to DateTime.Now instead of implicitely using the JS epoch, as the difference would be the same for any localized DateTime, just felt the clarity was worth it.

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.