User-Centric Javascript – How to Use it, How it Can Help You

Kayla gave us a great primer on user-centric design in her article, “The Art of User-Centric Web Design.” Design, however, isn’t the only thing that should centered around the user. The entire web experience should be user-centric, so let’s take a look at how you can use Javascript to support your user-centric goals.

Being a client-side language, Javascript is by definition somewhat user-centric. It offers us many incredibly helpful properties and capabilities to customize the user experience. We’ll go sans-jquery and work with pure Javascript, since it’s always a good idea to get a good understanding of what’s going on underneath anyways. Don’t worry if you’re a Javascript beginner – this article is targeted for beginners, although I’m sure old hands will pick up a new idea or two as well!

So, let’s go: here are 7 marvelous things you can find out about your visitors using Javascript.

Where They Came From – document.referrer

The referrer property is attached to the document object – it returns the url of the web page the user came from. Think about it – you can know where your visitors are coming from and respond accordingly! I’m sure you can imagine plenty of interesting uses for this one. Perhaps the most popular and useful is exemplified in the WPGreetBox plugin – presenting a custom message that welcomes your visitor. Of course, you could easily craft your own more efficient, personalized version that would work on any site, WordPress or not. You could even go as far as showing different content based on what the referrer was.

Because document.referrer returns a url, we’ll have to do a little parsing to come out with a domain name. Here’s one way you could do it:

var ref = document.referrer; //define as variable
ref = ref.substring(7); //strips "http://" (7 characters)
ref = ref.split("/"); //splits ref into array
ref = ref[0]; //we can then grab the first item in the array;

//Or you can declare it all in one line:
var ref = document.referrer.substring(7).split("/")[0];

// Then operate, based on what the domain is. If you have several different domains
// you want to react to, a switch statement is more efficient than if elseif elseif...

switch (ref){
	case '':
		//do something
	case '':
		//do something
	case '':
		//do something

What They’re Looking For – Grabbing GET variables

This one that Javascript isn’t often asked to do – accessing GET variables. Most of the time, you’ll want to respond to these on the server. Sometimes however, you’ll want to read the search query with Javascript, which is surprisingly easy. You could set up a little function like this:

var searchString =; //Javascript gives us a handy search property
searchString = searchString.substring(1); //Slice off the '?' at the beginning
var searchArray = searchString.split("&"); //Split the string into an array, using one item per variable

//Again, it's more efficient to declare it all in one line:
var searchArray ="&");

//Now we'll loop through searchArray and create an associative array called GET

var GET = new Array(); //We can't add items to GET unless it's defined
for (searchTerm in searchArray){
	searchTerm.split("="); //Divide the searchTerm into property and value
	GET[searchTerm[0]] = searchTerm[1]; //Add it to the GET array

Once you have a list of get variables you can do all sorts of spectacular things, like highlighting search terms or hiding/showing content – it’s really just up to your imagination.

How They Want It To Look – Stylesheet Switchers

There’s so much debate over fixed layout vs. fluid layout, dark vs. light design, etc., yet no matter what you pick someone won’t like it. What better way to make your visitor happy than to let them pick? A stylesheet switcher does just that – and on a portfolio, it can be an impressive way to show off your design skills. You’ll find lots of resources and plugins for stylesheet switching out there. Here’s how you might create a style switcher with pure Javascript:

function switchCSS(url){
	var linkElements = document.getElementsByTagName("link"); //get all link elements
	for (var i=0; 1 < linkElements.length; 1++){   //loop through them
		if (linkElements[i].getAttribute("rel") == "stylesheet"){  //if it's a stylesheet
			linkElements[i].setAttribute("href", url); //change the href

//Then, you could set up a select box with your stylesheets listed in it and bind the change event to it:
var stylesheetSelect = document.getElementById("stylesheetSelect");
stylesheetSelect.onChange = function(){
	switchCSS(this.options[this.selectedIndex].value); //pass the select value to our switchCSS function

So that’s a real simple way to do it. Be sure to remember this one, because this one will probably make the biggest difference for your visitors.

When They’re Looking At It – the Date() object

Wouldn’t it be neat to change the page based on the date or what time of day it is? Thanks to the Javascript date object, you can! The date object offers lots of helpful methods, and several that are specifically helpful for customizing the user interface. You could change your styles based on the time of day:

var currentHour = new Date().getHours; //The getHours method returns an integer between 0 and 23
if (currentHour > 5 && currentHour  12 && currentHour < 7){
	//Between 1pm and 8pm, do something else
}else if (currentHour  7){
	//Between 8pm and 5am, do something dark and scary (just kidding!)

You can also use do stuff based on the day of the week, or the time of year:

var weekDay = new Date().getDay(); //returns an integer between 0 and 6
var currentMonth = newDate().getMonth(); //returns an integer between 0 and 11

//Now you can evaluate just like you did with getHours, and display
//different content based on the day of the week,
//or change your blog theme seasonally - you get the idea!

And that’s the date object. Neat, huh? You can find out more in Mozilla’s Developer Reference

What They Did Last Time – the Cookie() object

Of course, you’ve heard of cookies before, but not that many people have actually worked with them. They’re an excellent way to store user data and provide a personalized, user-centric experience, beside being a lot of fun to play with. Document.cookie is a read/write reference, so that’s what you’ll refer to for both writing and reading cookies. I highly recommend that you read about cookies on, they have a marvelous explanation over there.

In short, cookies are written like this:

document.cookie = cookieName+ "=" +cookieValue+ ";expires=" +expirationDate+ ";path=" +cookiePath";

And read like this:

var cookieStart = document.cookie.indexOf(cookieName+ "=");
//search for the cookie name, including the equal sign

var cookieEnd = document.cookie.indexOf(";",cookieStart);
//find the semicolon that marks the end of the cookie string

var cookieValue = document.cookie.substring(cookieStart,cookieEnd);
//get a substring of document.cookie equal to the cookies value

//You can now refer to the cookie value in other parts of your script

Confused? Here’s a couple quick details:

  • cookieName and cookieValue are a key/value pair, both are strings
  • expirationDate is a GMT string of a time in the future- Remember the date object? It has three more handy methods: toGMTString(formats a date to a GMT string) and setDate(sets the date arbitrarily), and getDate(gets the current date), which you can use to define expirationDate like this:
    var expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + numberOfDaysInTheFuture).toGMTString();

    You don’t have to set an expiration date, but if you don’t the cookie will be erased as soon as the browser closes.

  • cookiePath is the path that the cookie is valid at, usually just ‘/’ to apply to the whole site

Once again, I haven’t gone into a very much depth here because it’s explained so well elsewhere, so feel free to check out Quirksmode’ Cookie Tutorial.

How Big Their Screen Is – Using Display Settings

Display settings are another big help (most of these are attached to the screen object). For example, if you were working with a fluid layout, you could use screen.width and/or screen.height (these return the absolute monitor size) to supplement fluid css techniques, or even switch stylesheets. Kayla wrote an excellent article for Smashing Magazine on fluid layouts, if you’re interested in finding out more about this (many of the tricks and tools mentioned there work by using Javascript to grab a screen dimension). An example of how to do this?

if (display.width < 1000){
//etc, etc.

Or, if you’re looking for window width/height rather than screen dimensions, you can do that, too. Outer window dimension can be grabbed safely on most browsers via window.outerHeight/window.outerWidth. The inner height is a bit trickier – reasonable browsers use window.innerHeight/window.innerWidth, IE 6 uses document.documentElement.clientHeight/Width, and the later IE’s use document.body.clientHeight/Width.

You can read about other helpful screen properties at W3Schools. When it all boils down, adjusting a web page based on user display factors is just a good, user-centric practice that can make a visitor like your site better, even if they don’t know what’s happening behind the scenes.

What They’re Browsing With – the navigator object

While it wouldn’t be needed in a perfect world, the navigator object is great because it allows you to adjust your page based on the user’s browser. The good part? You can keep your css valid by not resorting to IE hacks, and your page will still look good.

The two most relevant navigator properties are appName and appVersion. For example, you could define a variable like so:

var ie6 = (navigator.appname == "Microsoft Internet Explorer" && navigator.appversion.indexOf("MSIE 6.0") != -1);
//First, we check if the name is indeed "Microsoft Internet Explorer
//navigator.appVersion returns a whole string of info, so then we search for
// MSIE 6.0, to figure out if the client is using IE 6 or some other version

//Later, we can run a conditional:
	//and adjust our styles here to fit a certain cruddy old  browser

This just another example of using Javascript to center a web experience around each user, and it’s a great option for taking care of browser bugs without screwing up your CSS. By the way, you might want to checkout the hilarious article, “15 Amazing Anti-IE Resources“, in case you didn’t see it.

Wrapping Up

That’s it, folks! Don’t blow this one off, though – applying the principles of user-centricity to your Javascript is very important. It really does make a difference to people to see some nice, friendly variety and customized uniquely for them. It’s the difference between the big chain store that just sells you stuff cheap and the little local place that really cares. Be the friendly local!