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.


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 a 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 tesing 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. Pushup detects the version of the client and briefly flashes a notice with a link to download an update. The entire package is fairly lightweight (only 11kb, zipped) and includes the images, sylesheets and JavaScript files to run. Implementation and customization information is provided on the download site, in addition to ports of the function for dojo and jQuery.

This doesn’t really help users whose IT departments prohibit them from updating, but if it helps those who are unaware that there is a better web experience to be had then it is worthy of praise and support.


UPDATE

VICTORY!!! Even Microsoft is denouncing IE6. Track the downfall of this archaic software at IE6 Countdown.


sIFR + jQuery = Custom Typography Without Image Replacement

If you haven’t heard of it already, sIFR lets you appease all those designers by integrating custom fonts onto your standards-compliant web page without turning them into images. On its own, it’s not a small or straightforward undertaking, requiring a number of additional CSS and JavaScript files to function. However, the recent release of the sIFR jQuery plug-in should make it more accessible to developers:

First, jQuery makes finding the item(s) that you want to replace as easy as using CSS. Then, the jQuery sIFR Plugin does all the work of figuring out the text, files, sizes, colors, and any other configurations needed for the conversion. The jQuery sIFR plugin is fully configurable and can choose how little or how much you want to customize the display of the sIFRed text. Finally, the jQuery Flash Plugin does a most excellent job of embedding the sIFR flash into your web page. After all is said and done, you should have beautiful sIFR replaced text with consistent behavior across all major browsers.

All the resources are available for download from the developer’s site, as well a simple API and usage examples for easy customization.


UPDATE

While sIFR may have its uses it also has a number of serious drawbacks. Check out some of the emerging web typography technologies, including Cufón, @font-face and Typekit.


The Evolution of Sizzle

Among the many interesting things discussed in the interview with Sitepoint, John Resig again brought up a project titled Sizzle. No, he’s not talking about adding POW BANG SHAZAM to our web layouts; it’s an initiative to create standardized and easily-implemented CSS-based selectors for JavaScript.

Aside from its lightweight and extensible nature, jQuery’s ability to easily assign behaviors and attributes to custom-created arrays of elements without much hassle is one of its most appealing features. Using a similar scheme for other libraries, frameworks or even in stand-alone cases would not only simplify programming (goodbye document.getElementsByTagName “for” loops!) but would improve the language as a whole by making scripts more readable and accessible.


Using jQuery for DHTML Drop-Down Menus

You may have heard of the Suckerfish Dropdowns featured on A List Apart (which use CSS and JavaScript along with valid HTML to create vertical or horizontal “drop-down” menus) and the the extended revised version Son of Suckerfish, but if you’re already using the jQuery library on your site the code to mimic the :hover pseudo-class gets even simpler.

Instead of:

1
2
3
4
5
6
7
8
9
10
11
12
13
sfHover = function() {
  var sfEls = document.getElementById("nav").getElementsByTagName("LI");
  for (var i=0; i<sfels .length; i++)="" {="">
    sfEls[i].onmouseover=function() {
      this.className+=" sfhover";
    }
    sfEls[i].onmouseout=function() {
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
</sfels>

You only need:

1
2
3
4
5
jQuery('#nav li').hover(function(){
 	$(this).addClass('sfhover'); //mouseover
 }, function(){
 	$(this).removeClass('sfhover'); //mouseout
 });

or, simpler yet:

1
jQuery('#nav li').bind("mouseover mouseout", function(){ $(this).toggleClass('sfhover'); });

Such is the beauty of using css-style selectors to build an array of affected elements. Of course, you must make sure the code is wrapped in $(document).ready(function(){…});, but there is no need to modify the window.onload event in this example. Otherwise, refer to the code provided in the above examples to get your markup and formatting styles in place.


Cross-browser Debugging

A number of code monkeys that I know use the Web Developer Toolbar in conjunction with the Firefox browser. The addition of a menu/toolbar is quite handy, especially the abilities to enable or disable JavaScript and CSS, and providing line guides and rules to ensure proper alignment of layout elements. Despite being so comprehensive in its features, it lacks the ability to view the loaded assets of a page, explore the DOM tree, or view box model for any element.

This is where Firebug comes in, allowing you to not only inspect an element with one click to reveal all of its defined and inherited styles and attributes, but also to edit the properties in the browser without having to make changes to the source documents.

With the most recent version of Firefox, I had issues with viewing the attributes and styles of the A element, but I found that an upgrade to beta version 1.1 solved the problem.

And for testing in Safari, Opera or dreaded Internet Explorer, they offer Firebug Lite that can be implemented via Javascript file to take advantage of the console object, which can be very useful for debugging JavaScript. I plan to write in further detail later about the wonder and majesty of this feature, so stay tuned.

If you enjoy the inspection aspect of Firebug, there is another cross-browser tool available called pi.debugger. It does not work with Safari (at least not version 3) but performs like a champ on IE, Camino and Flock. The script can be downloaded to your workspace or linked to from the Google source page in the link.

Given the number of options and resources available, the task of finding that one property that is throwing your whole layout off should be made that much easier. Happy hunting!

ADDITION: Westciv has released a slick bookmarklet called XRAY that lets you inspect elements in almost any browser.