Parse the Querystring with jQuery

In a number of the web applications I have recently been working on, I have found it necessary to dissect the URL and access the various parts of the querystring. While the window.location object already has some useful properties, I wanted to be able to reference the indices using bracket or dot notation so I put together this handy plugin for my favorite JavaScript library, jQuery.

Plugin

1
2
3
4
5
6
7
8
9
10
11
12
jQuery.extend({
  parseQuerystring: function(){
    var nvpair = {};
    var qs = window.location.search.replace('?', '');
    var pairs = qs.split('&');
    $.each(pairs, function(i, v){
      var pair = v.split('=');
      nvpair[pair[0]] = pair[1];
    });
    return nvpair;
  }
});

Usage

Assuming the URL is http://mydomain.com/page.html?foo=bar&somevalue=myvalue, you can either access an index directly jQuery.parseQuerystring().foo, or by setting a variable, like this:

var qs = jQuery.parseQuerystring();
//qs['foo'] == "bar"
//qs.somevalue == "myvalue"

The goal of extending the jQuery object with this utility (meaning that it does not require a selected set of elements, and in this case does not even require an argument) was flexibility, however it can easily be converted to a function in the global namespace. If you would rather download the files, they are zipped up and ready (zipParseQuerystring jQuery Plugin).

Are there additional operations you’d like to see added to this, or relating to the URL and querystring? Let me know in the comments.

Update: Code posted to GitHub as a Gist snippet


Toggle Text Field Values with jQuery

UPDATED: Project moved to Git!

I saw this post on the CSS Tricks Snippet Feed which addresses a commonly desired form behavior: to provide default text in an INPUT element that disappears when the user enters that field. The example provided works, but I have a couple issues with it:

  1. Uses inline JavaScript, and must be reapplied to each element affected
  2. Repeats the contents of the value attribute
  3. The default text is not replaced if the user exits the field without entering new data

So I created a possible solution, using jQuery:

HTML

1
<input type="text" value="Place default text here" />

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
jQuery( function(){
  $( 'input[type="text"]' ).each( function(){
    $(this).attr( 'title', $(this).val() )
      .focus( function(){
        if ( $(this).val() == $(this).attr('title') ) {
          $(this).val( '' );
        }
      } ).blur( function(){
        if ( $(this).val() == '' || $(this).val() == ' ' ) {
          $(this).val( $(this).attr('title') );
        }
      } );
  } );
} );

This script first iterates over each of the text input to assign a semantic text attribute, helpful not only in storing the default value, but also providing a tool-tip for reference as the user interacts with the page. It then assigns behaviors for both the onfocus and onblur events, eliminating the need to respecify data for comparison. The script is cleanly separated from the markup and, using jQuery, additional specifications may be made so as to only affect children of a particular FIELDSET or only those that possess a certain class.

I hope you find this snippet useful, and feel free to comment if you have additional information to share.


UPDATED!

We, as designers and developers, cannot help but go back to review our sites and code to make updates and revisions as our skills, philosophies and tastes change. In this spirit, I would like to offer an alternative to the above JavaScript snippet. The one above, in my opinion, is lacking in the following ways:

  1. Applies the behavior to all input[type="text"] elements indiscriminantly.
  2. Overwrites any existing title attribute content
  3. Does not account for existing text field values resulting from pre-population or validation.

So with that in mind, here’s the new solution:

HTML

1
2
<input type="text" title="Place default assistive text here (e.g. First Name)" />
<input type="text" title="Default assistive text (e.g. E-Mail Address)" value="invalid@ddr.ess" />

jQuery Plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.fn.toggleField = function(){
  return this.each(function(){
    var $this = $(this);
    if($this.val() === '' && $this.attr('title') !== ''){
      $this.val($this.attr('title'));
    }
    $this.bind('focus blur', function(){
      var $this = $(this);
      if($this.val() === $this.attr('title')){
        $this.val('');
      }else if($this.val() === '' || $this.val() === ' '){
        $this.val($this.attr('title'));
      }
    });
  });
};

JavaScript

1
2
3
jQuery(document).ready(function(){
  $('input[type="text"]').toggleField();
});

By converting the behavior into a plugin, it becomes chainable and more flexible. Perhaps in a future version it would be useful accommodate additional field types or textarea elements. I have also packaged the plugin for download (zipToggleField jQuery Plugin). I look forward to seeing your questions or suggestions in the comments below!

Project Moved to Git

After further review and consideration, I decided to make some more changes to the plug-in to take advantage of some of the new features promoted in HTML5. Specifically the placeholder attribute, since this is essentially the behavior that we are trying to mimic. Here is an example:

<label for="email">Email:</label>
<input type="email" id="email" name="email" title="Enter a valid email address" placeholder="account@domain.tld"/>

The previous zip file will remain available above, but the toggleField.jquery.js project updates will progress on GitHub instead. Thanks to everyone for your suggestions and support!


Innovative Layouts and Content Transitions with JavaScript

I started following @jquery on Twitter sometime ago, and they have provided a lot of great links and information.

One interesting link is to an article about methods for presenting information and creating systems to enhance user experience:

Delivering informative structure is the primary task an interactive user interface should be able to cope with. The more intuitive layout structure is designed, the better users can understand the content.

Read the full article on Noupe.


Examples of jQuery In Action

The jQuery foundation has created a new site showcasing designs that Use jQuery. They currently have only about 30 samples organized by effect/function category, but they do accept submissions so show off that great interface or behavior that you’ve created!


Logo Design Inspiration

I recently stumbled upon a list of 54 Kick Ass Creative Logos which in turn led me to Logo Faves, who accept submissions from designers, and describe themselves as:

A collection of best designed logos around the web is showcased in Logo Faves. We don’t want to be like other Logo repositories, our idea is to bring you all the best of best logos.

Also relying on suggestions and entries from webmasters to compile its collection, Web2.0 categorizes over 100 logos and displays the user-ratings for each.

FontFeed took a bit of a different approach in grouping popular web logos by style, and even though the article was published in 2006, it is still a great source of information.

So what are you waiting for? Check out some of the design resources over at For Web Designers and submit your best work!

Of course, you could always just use a pre-configured generator.


21 Useful Font Utilities

Looking for the perfect font system for your design, compare different styles side-by-side, or embed non-”web-safe” typeface in the layout? There’s a web application for that.

Highlights include:

  • STC fontBROWSER – an online tool for browseing varoius fonts and viewing how your selected text looks with each.
  • WhatTheFont – upload any image with characters and instantly find the closest matches within their database
  • Typetester - compare different fonts for the screen, up to three at a time
  • Font Burner – replace text on your page with one of 1000 vector-based fonts with a simple block of code

Check out the entire list of 21 Typography and Font Web Apps You Can’t Live Without.


Pushup Makes the Web Stronger

Every web developer that I know is sick and tired of making compromises and hacks to accommodate Internet Explorer 6 and other browsers that are not standards compliant.

While graceful degradation (or progressive enhancement, depending on which philosophy you subscribe to) will continue to be par for the course for the forseeable future, it would be great if we could fully take advantage of the available technologies and minimize crosss-browser testing costs in our project budgets.

To this goal, Nick Stakenburg released a script that gently alerts the user that their browser could use an upgrade.

Continue reading…


Open Call: Eclipse

My editor of choice lately has been Eclipse, even though I don’t know anything about Java. The PDT project for PHP development is wonderful for keeping track of variables and functions and classes that my site/application uses, and it has just enough panels that provide information about the projects that I am working on, as well as the attributes for just about every HTML/CSS element.

Coupled with Subclipse for Subversion source control, Eclipse is my one stop shop for all things web development.

Continue reading…