Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Forms & JavaScript Living Together in Harmony

Rated 4.48 (Ratings: 31) (Add your rating)

Log in to add a comment
(44 comments so far)

Want more?

 
Picture of Jeff Howden

Jeff Howden

Member info | Full bio

User since: December 13, 1998

Last login: November 30, 2008

Articles written: 21

Most developers don't surf the web with JavaScript turned off on purpose (with the obvious exception of the aardvark) so they probably aren't aware of the devastating effects caused by the irresponsible use of JavaScript when working with forms. Fortunately, there are rarely instances where this lack of respect for the non-JavaScript users is necessary. By exposing you to some of the common examples of forms that are hostile to non-JavaScript users and the ways these same forms can be implemented to be friendly to non-JavaScript users, I'm hoping you'll see the wisdom in carefully planning your use of JavaScript with forms.

What are some examples of irresponsible use of JavaScript with forms?

Look Ma! No submit button!

The first and most common is the use of a dropdown menu as navigation (See Figure 1 below). Aside from the obvious usability and accessibility concerns inherent in this design faux pas, some developers unnknowingly render the navigation useless to non-JavaScript users by omitting a submit button. Often the argument for not including the submit button is that it uglies the design. I'd argue that the dropdown menu isn't much prettier, even with lots of css styling applied to it. However, most designers and some developers are vain and would rather sacrifice usability for the sake of "the look". So, non-JavaScript users suffer.

Figure 1 — Example of using dropdown menus for navigation with reckless abandon at Chevrolet.com.  (click to see a larger version)Figure 1: An example of a site that uses dropdown menus as navigation, with no apparent means for non-JavaScript users to get to the same content. You might be thinking the blue square in the top-right of the figure is a submit button. Don't let it fool ya. Just because it's sitting next to a dropdown menu doesn't mean it has anything to do with it. It's actually a link. See what I mean.

<lisp>The submit buttons must be purple and do that faaaabulous image swapping thingy like the navigation!</lisp>

The second is the gratuitous abuse of branding — colors and rollovers spilling over in to submit buttons (and all too often the form elements themselves, thanks to CSS). As if graphical submit buttons aren't bad enough, some designers practically demand the graphical submit buttons rollover when the user mouses over them (Figure 2 below is a fine example of this). Unfortunately, too many developers are stuck using wygiwyd software and/or are unaware of the possibilities available in the latest browsers that don't require neutering the form for non-JavaScript users in order to quell the unrelenting demands of the designer. If they do seek help from other developers in finding a solution, the suggestion is almost always to wrap an image with a link that calls the submit() method. Too bad that's not the solution.

Figure 2 — Example of castrating a form by forcing the user to have JavaScript enabled to submit it.  (click to see a larger version)Figure 2: An example of a site that places design element behavior over usability and accessibility. If I don't have JavaScript enabled, I can't submit the form by clicking on the "Submit" button. In Mercedes-Benz USA's favor is that you can still submit the form by pressing the ENTER key on the keyboard when the cursor is in the Zip Code field. See what I mean.

That's not how you validate a form?

There are right ways to perform form validation with JavaScript and then there are wrong ones. All too often, developers implement validation the wrong way. For JavaScript enabled users, the result is the same. However, done the wrong way, non-JavaScript users are left with a form that does absolutely nothing when they click the submit button. If you read no further, take with you the knowledge that the only ways to properly perform form validation with JavaScript is to use the onsubmit event handler of the &lt;form&gt; tag or the onclick event handler of a non-graphical submit button to call a function that returns a boolean of true or false.

So what's the solution?

The most obvious solution is to not use JavaScript at all. However, that usually negatively impacts a user's experience by forcing a round-trip to the server just to get the form back with error messages indicating required fields they didn't enter data or pattern-matched fields with syntactically invalid data. Besides, this article is about using JavaScript responsibly with forms — not about not using JavaScript at all.

Taming the dropdown menu

If you insist on going against evidence that using dropdowns as navigation is a bad idea, at least include a mechanism to make them usable by your non-JavaScript users. If you're at least marginally conscious of usability issues, you'll resign yourself to not using the onchange event handler to change the page. That means you'll likely have some other mechanism like a button or link that finds the user's selection and changes the page to the one they selected. Making this work for non-JavaScript users will require only a small amount of work. You'll need to change that link or button to a regular submit button. You can even use a graphical submit button if you prefer. Rather than calling the function from the submit button though, you'll need to move the call to the onsubmit event handler so this will work with the most browsers possible (Some browsers <cough>Netscape Navigator 4.x</cough> don't support onclick event handlers on graphical submit buttons). You'll also need to reference a server-side script in the action attribute that the non-JavaScript users will submit the form to. This server-side script will take the value they selected from the dropdown menu and perform a simple redirect. See Listing 1 for some example JavaScript illustrating this technique. Listing 2 contains some example ColdFusion code that could be used to facilitate that server-side portion of this solution.

Listing 1 — The HTML & JavaScript for the client-side processing 

<script language="JavaScript" type="text/javascript">
<!--
  function navigateForm(obj)
  {
    if(obj.selectedIndex != -1 && obj.options[obj.selectedIndex].value)
      top.location.href = obj.options[obj.selectedIndex].value;
    return false;
  }
//-->
</script>

<form action="navigate.cfm" method="post" onsubmit="return navigateForm(this.form.navigateSelect)">
  <select name="navigateSelect" id="navigateSelect" size="1">
    <option value="">Choose One</option>
    <option value="/">Home</option>
    <option value="/products/">Products</option>
    <option value="/faq/">FAQ</option>
    <option value="/about_us/">About Us</option>
    <option value="/contact_us/">Contact Us</option>
  </select>
  <input type="submit" value="Go" />
</form>

Listing 2 — The ColdFusion for the server-side processing 

<cfparam name="form.navigateSelect" default="/">
<cflocation url="#form.navigateSelect#" addtoken="No">

If you just can't live with the submit button being visible to your JavaScript enabled users, leave some room in the design for it and only show it to non-JavaScript users by wrapping it in a &lt;noscript&gt; tags. See Listing 3 below for an example of the HTML.

Listing 3 — Hiding the Submit button from JavaScript-enabled users 

<form action="navigate.cfm" method="post" onsubmit="return navigateForm(this.form.navigateSelect)">
  <select name="navigateSelect" id="navigateSelect" size="1">
    <option value="">Choose One</option>
    <option value="/">Home</option>
    <option value="/products/">Products</option>
    <option value="/faq/">FAQ</option>
    <option value="/about_us/">About Us</option>
    <option value="/contact_us/">Contact Us</option>
  </select>
  <noscript>
  <input type="submit" value="Go" />
  </noscript>
</form>

[Note: The &lt;noscript&gt; tags were introduced with JavaScript1.1. Therefore, any browser that doesn't support JavaScript1.1 will ignore the &lt;noscript&gt; tags and attempt to display anything contained within them. As the only browser this really affects is Netscape Navigator 2.x, you're not likely to experience this problem.]

Appeasing The Demanding Designer

Provided you're willing and able to make this functionality available for only a portion of your audience, you can give the design what he or she wants without crippling the form for non-JavaScript users. Don't let this notion of some visitors missing out on the foofoo eye-candy stop you from doing the right thing. Though the numbers could vary for your own site, I'm probably talking about 5% or less of your audience not getting the rollover effect the designer is so proud of. However, all of your users, despite their support for JavaScript, should be able to use the form.

Before we charge off into some example code showing how to accomplish this, let's take a look how it's usually accomplished in a manner that makes it unusable for non-JavaScript users. Listing 4 below contains HTML for a very small form.

Listing 4 — Snazzy but an obstacle for some 

<form action="/login.cfm" name="loginForm" method="post">
<input type="text" name="username" value="" /><br />
<input type="password" name="password" value="" /><br />
<a href="JavaScript:document.loginForm.submit()"
    onmouseover="rollOver('loginButton', 'on')"
    onmouseout="rollOver('loginButton', 'off')"
><img name="loginButton"
    src="images/login_off.gif"
    width="88"
    height="31"
    border="0"
    alt="Login"
/></a>
</form>

So how do we remedy this situation so it's usable by all visitors to our site? Simple — remove the &lt;a&gt; tag and use an image submit button instead of a regular image. We'll also move the onmouseover and onmouseout event handlers to the image submit. Most (like 95+%) of the browsers that will be visiting your site will support these event handlers on the image submit. Those that don't will simply get a normal, "boring" image submit button. See Listing 5 below to see what the code in Listing 4 looks like after this conversion.

Listing 5 — Snazzy and usable too 

<form action="/login.cfm" name="loginForm" method="post">
<input type="text" name="username" value="" /><br />
<input type="password" name="password" value="" /><br />
<input type="image"
    src="images/login_off.gif"
    width="88"
    height="31"
    border="0"
    alt="Login"
    onmouseover="rollOver('loginButton', 'on')"
    onmouseout="rollOver('loginButton', 'off')">
</form>

"Are you an idiot? Tell me you didn't just put that there." or Validating Form Data

The last one that's so often funked up by irresponsible JavaScripters is form validation. The sad thing is that they mess it up not out of spite, but because they don't understand the right way to do it. The wrong way to do it almost always involves the use of the submit() method. So, what exactly is the right way?

The right way involves building the form and its functionality from start to finish without any JavaScript. Complete all your server-side checking and processing. Then, come back and add your client-side checking to improve the user's experience. It's as simple as adding an onsubmit event handler to your &lt;form&gt; tag. Since this event is cancellable, we preface our validation function call with a return statement. The validation function will return a boolean value of true or false finishing off this return statement. A return true statement will result in the default behavior — the form submitting. Conversely, a return false statement will result in the form submission being aborted. See Listing 6 below for an example of how the function in the onsubmit event handler is called.

Listing 6 — How to call your validation function with the onsubmit event handler 

<form
 action="/login.cfm"
 name="loginForm"
 method="post"
 onsubmit="return validateForm(this)"
>
[Note: See my article on event handlers and cancelling events called "JavaScript: The Point of No Return!?" for an overview of these concepts.]

Let's take a look at our form validation function — validateForm() — to see how it works. Before we do though, it'd be a good idea to see the form we'll be working with. For simplicity, we'll be validating a simple login form with username and password fields. See Listing 7 below for the HTML for this login form.

Listing 7 — Our Login Form 

<form
 action="/login.cfm"
 name="loginForm"
 method="post"
 onsubmit="return validateForm(this)"
>
  <label for="username"
  ><u>U</u>sername</label> 
  <input type="text"
         name="username"
         id="username"
         tabindex="1"
         accesskey="u"
         value="" /><br />
  <label for="password"
  ><u>P</u>assword</label>
  <input type="password"
         name="password"
         id="password"
         tabindex="2"
         accesskey="p"
         value="" /><br />
  <input type="submit"
         tabindex="3"
         accesskey="l"
         value="Login" />
</form>

When the user submits the form our validateForm() function is called (Follow along with the code in Listing 8 below). The function creates a couple of variables local to the function that it'll use for storing the return value (returnValue), the concatenated error message (errorMessage), and which field needs to receive focus if the form doesn't validate (focusField). Then the function checks the username and password fields for values. If either field is blank, it adds some text to the errorMessage variable, sets the focusField variable to the current field if it hasn't been set yet, and changes the returnValue variable to false. If both fields have values then returnValue keeps its initial value of true. This boolean is then returned to the calling event handler by the return statement on the last line of our function. The event handler uses this boolean value that comes back from the function in combination with the return statement just before the function call and allows submission if the boolean is true or halts submission if it is false.

Listing 8 — validateForm() 

<script language="JavaScript" type="text/javascript">
<!--
  function validateForm(form)
  {
    var returnValue = true;
    var errorMessage = 'The following field(s) are required and do not contain any information:\n\n';
    var focusField = null;
    if(!form.username.value)
    {
      errorMessage += ' - Username\n';
      if(!focusField)
        focusField = form.username;
      returnValue = false;
    }
    if(!form.password.value)
    {
      errorMessage += ' - Password\n';
      if(!focusField)
        focusField = form.password;
      returnValue = false;
    }
    if(!returnValue)
    {
      alert(errorMessage);
      if(focusField)
        focusField.focus();
    }
    return returnValue;
  }
//-->
</script>

In conclusion

I've only covered the most common JavaScript mistakes made when working with forms. There are lots more out in the wild that frustrate non-Javascript users to no end. I hope this article has shown that it doesn't have to be this way and encouraged you to be the best developer you can be. After all, forms and JavaScript really can live together in harmony.

.jeff

Jeff Howden (.jeff) is a web developer working for Vos & Howden, LLC in Portland, Oregon where he's partnered with long-time colleague, Anthony Vos. His skills include ColdFusion, JavaScript, CSS, XML, relational databases, and much, much more. His biggest professional accomplishments include, but are not limited to:

  • building a ColdFusion-based e-commerce solution for Mt. Bachelor that transacted over $1.62 million dollars in September 2001 with 0 (yes, that's zero) ColdFusion errors and then an almost completely rebuilt version transacted $2.86 million dollars in September 2002.
  • being asked to be a Technical Editor for the ColdFusion MX book, Inside ColdFusion MX from New Rider's Publishing company.
  • being asked by BrainBench to perform quality control on their JavaScript 1.5 certification test after receiving the highest beta test score out of 200 testees.
  • managing the server that hosts evolt.org and withstanding a slashdotting that brought over 1,000,000 hits to the site, over 10 gigs of data transfer, and an average in excess of 2300 unique visitor sessions per hour, all within a 24-hour period and the server never hiccuping once.

Pity!

Submitted by themadman on June 3, 2002 - 11:47.

Oh, how I miss the "email article to friend" feature. :(

Excellent article, Jeff. The abuse of Javascript in form submissions is rampant, I'm afraid. It's usually due to the programmer's "It works on my bloody machine, doesn't it?" mindset.

login or register to post comments

Chevrolet

Submitted by kirkaracha on June 3, 2002 - 14:02.

If I have JavaScript turned off, all I get on the Chevrolet site is a blank white window. (IE 5.1/OS X)

login or register to post comments

Yay!

Submitted by bobince on June 4, 2002 - 18:09.

Excellent article. Too many people are doing this wrong, and it's really not difficult to do it right.

You cannot rely on JavaScript, ever. Even if it's enabled, there are any number of reasons a script might not work, so you'd better make sure the page works without it as well.

BTW for anyone who's wondering why onchange-submit select boxes are such a Bad Thing, remember navigating a select from the keyboard generates a change event for every arrow up/down movement. So changing the page on the first onchange will make keyboard navigation practically impossible. Never mind the disability/accessibility issues: even many laptop users will be screwed.

login or register to post comments

Superb article

Submitted by pwaring on June 7, 2002 - 08:04.

I think you've covered just about everything there, I guess I won't be needing to write a forms/javascript tutorial after all! Well done.

login or register to post comments

this is why people hate usability specialists

Submitted by figment88 on July 3, 2002 - 21:20.

you know when I surf with my monitor turned off not only can I not submit forms, but I can't even see the page. Proper coding requires each site to do a monitor check and if the monitor is off to automatically transform the site into speech and read it aloud.

login or register to post comments

Why stupidity should be painful

Submitted by Jeff Howden on July 4, 2002 - 04:03.

Figment88,

It's amazing you were able to post your comment, seeing as how you're monitor was most likely off (we don't bother checking ;p) and posting your comment requires you to submit a form. It's even more amazing how you managed to read the article. Then again, your comment doesn't really indicate that you read the article or comprehended it if you actually bothered reading it first.

To address your baseless comments towards usability specialists (something I'm not too quick to label myself actually), I'd have to say that there are some base assumptions one has to make whenever trying to determine the usability or accessibility of something. For instance, you wouldn't include people without any computer access in an accessibility study of an Internet site. That would be ridiculous and unnecessarily skew your results. The same goes for your crack about the monitor. If the user is using the computer, the only reason they'd have their monitor off is because they're completely blind and are already using a screen reader. Otherwise, it's a fairly safe bet that their monitor is on. Well, I suppose we can make an exception for you if that'd make you feel better.

Anyway, what was your point again?

.jeff

login or register to post comments

I think I understood

Submitted by figment88 on July 4, 2002 - 12:04.

Basically the article is telling me I should think about changing my web coding to account for browsers without JavaScript. I think the quote "The most obvious solution is to not use JavaScript at all" sums it up pretty well.

However, the article never tells me - other than a throwout number of under 5%--how many people visiting web sites don't have JavaScript. Well as someone who has looked at the data for a large number of web sites, I can tell you it is generally well under 2% and going down down down. Further, you got to ask yourself who the heck are these people without JavaScript -- are they really in my target audience? The answer to the question is 1) people with diasbilities (this is going down really quick with better tools), people surfing through some type of transient proxy such as an anonimizer or a kiddy filter, and privacy kooks. For almost every web site, I believe people surfing without JavaScript are not likely to buy or do whatever else you want them to do on your site.

So, how much time and other resources should I devote to these people. If I follow your regimen, I have to spend more time thinking about my code and a lot more time QA'ing my code. In addition, some of your suggestions require more server processing time and consequently slower page downloads -- what's the tradeoff here? Oh, if I bend over backwards to accomodate people without JavaScript, I can lower the usability for all my visitors. Yes, there are customers that you would rather your competition have instead of you.

As to my supposedly baseless comments about usability specialists. I have met and worked with hundreds of people working on web site usability, and in numerous occasions they complain about not being respected within their organizations. Why? Well one reason is that they make these hard-and-fast rules with no consideration to ROI, brand, or other people's time. While I think the majority of advice from usability specialists is really good, there is a certain amount that just advocates bringing everything down to the lowest common demoninator for no reason but uniformity.

I wonder if the people who do Standards and Practices for television networks convince themselves that they are respected by the writers and producers becuase they ensure the quality of the show.

BTW, I highlighted the quote above using the "b" tag instead of "strong". Even though, the concept of bold is meaningless to non-visual browsers, I believe it is still the right thing to do.

login or register to post comments

Cost-justifying Usability

Submitted by MartinB on July 4, 2002 - 16:38.

I have met and worked with hundreds of people working on web site usability, and in numerous occasions they complain about not being respected within their organizations. Why? Well one reason is that they make these hard-and-fast rules with no consideration to ROI, brand, or other people's time.

Required reading for Usability people: Cost Justifying Usability. But the trouble tends to be from the other side too, which is a This is a waste of time and ruins my design religeous argument.

And to make it even, and answer:

For almost every web site, I believe people surfing without JavaScript are not likely to buy or do whatever else you want them to do on your site.

the required reading is The Business Case for Accessible Web Design. Roughly 8%-10% of most national populations will have a disability which will be supported by following the WAI guidelines. I've yet to see any simplistic causal link between disability and a failure to be a consumer.

Thirdly, while fire your least profitable customers is an oft-quoted self-fulfilling prophesy, I wonder if that too is too simplistic. I've been looking at some research this week talking to 'less profitable' customers who expressed astonishment that that's how they were seen, and asked why on earth the company in question didn't just raise their prices. And this is particularly so if you think of business as a relationship, not a conquest. These people pay your fixed costs, remember.

I've a case study of a business who took the 'Fire your least profitable customers' approach and wondered where their revenue had gone. Meanwhile, a competitor spotted this and set a strategy based on these customers still want to shop - lets change the propostion to something that works for both of us. did rather well out of it.

Think Lifetime Value... and remember that cost to serve online is substantially less than via almost every other channel.

login or register to post comments

ROI of testing & Javascript

Submitted by MartinB on July 4, 2002 - 17:18.

Another couple of things to think about in your ROI calculation:

  1. If you're using Javascript to validate your forms, and not also validating on the server, then you're wide open to a bunch of security issues around trusting the input to the server to be what you expect. If, however, you're validating on the server then you're already doing the bulk of the testing required for non-Javascript users.

    In fact, as server-side validation is a non-optional element, isn't it your insistence on using JS which imposes the additional testing burden which requires cost-justification?

  2. Taking that one step further, experience shows that it is quicker and cheaper both in initial development time and also in future development (through greater flexibility) to use coding standards which adhere to accessibility and HTML standards. So the ROI case needs to be made for any variation from it.

  3. In some countries, being inaccessible to people with disabilities is illegal in many circumstances. In those countries where the precendent or statute is clear that this applies to online access as well as offline acccess, losing a suit blows a hole in your ROI.

    In those countries where it's not clear whether accessibility applies online, it blows an even bigger hole in your ROI when your lawyer sits there for a few hours, comes back with Dunno and recommends either taking it to a protracted court case, or redeveloping the site to be on the safe side.

  4. Today an airline site lost a sale from me. Their flight booking app was hanging on the form submit in IE (standard company install - no problems anywhere else, nothing silly going on with preferences). So I cracked open Lynx, filled in the form and couldn't submit it because the submit was a link wrapped in JS calling a submit() method. So I booked with a competitor instead.

    That one lost sale was UK£5000-worth (because it was for myself and several colleagues, flying business class). I believe that that one sale would more than pay for the additional development and testing time required to implement a pointless Javascript function.

    How many lost sales would you excuse to the client as privacy kooks? I would question either the soundness of your judgment or your honesty with your client if you're not prepared to admit the possibility of genuine lost sales through the vanity of demanding Javascript.

  5. I've worked with some of the most brand-focused people you'll ever meet in a year working with a drinks company whose major business focus is on brand values. The sites we replaced were all heavy on Flash, frames, Javascript and text rendered as images, with no alternative versions (or indeed alt attributes for images).

    The client need we uncovered was that these sites weren't doing the job in either brand values nor customer relationship building areas. Depending entirely on inaccessible technologies was ensuring that the entire sites weren't passing ROI criteria.

    So we replaced them with sites which were much more accessible. However, because the design company we worked with insisted, the submit buttons on our forms (success in which made or broke the business case) were all JS-only images to provide pretty rollovers. So when the sites weren't meeting KPIs, can you guess what these brand-obsessed clients demanded? Yes, that the rollovers were removed. Now we did a nice half-way house for them, and wrote in the JS version with document.write(), and the non-JS version with noscripts, which made everyone happy. Particularly as the numbers of people buying and registering on the various sites quickly returned to the forecast levels.

    If you've been reading anything about contemporary brands, you'll know that the major emphasis for brands now is not how it looks, but the experience the brand provides. And an experience where it doesn't work for groups of consumers is not a good oneGuess what, bub. Usability and Accessibility are brand values.

So given that requiring Javascript (as opposed to using it in a degradable way) meets neither ROI nor brand demands, why would you do that?

login or register to post comments

Great Article -Low Functionality

Submitted by romeo on July 9, 2002 - 08:43.

I head up an IT Dept for a manufacturing company. "E-mail this article to a friend" makes it easy for me to send great articles to my dept. I love those buttons for their functionality, please bring it back. Remember Evolt.org is all about functionality!

login or register to post comments

Need More Info...

Submitted by nvrau on July 20, 2002 - 22:29.

Please supply the function code for rollOver.

Will this work in Opera? I like to use Opera but a tremendous number of sites have JavaScript errors only in Opera.

TIA,
Brian

login or register to post comments

RE: Need More Info...

Submitted by Jeff Howden on July 21, 2002 - 02:07.

Brian,

Please supply the function code for rollOver.

You can find code for the rollOver() function in my members.evolt.org code section. The rollOver() function is designed to be used in tandem with the preLoad() function on the same page, though it can definitely be used independently if you want to manually setup the image preloading.

Will this work in Opera? I like to use Opera but a tremendous number of sites have JavaScript errors only in Opera.

The functions will most certainly work in Opera.

Since you mention that alot of scripts cause errors in Opera, let me throw out something that I didn't really highlight in my article. If you do a good job of making your apps/pages work without scripting, whether or not errors are thrown in Opera the user should still be able to use the site. However, if you also are good about object and support detection you won't be causing errors for Opera users.

Good luck,

.jeff

login or register to post comments

Thank you SIR, May I have another...

Submitted by nvrau on July 21, 2002 - 13:54.

Jeff,

I am sorry to say, that did not help...

Can you send me a link to a page where I can view working code? I have serveral questions which I could only ask if in person. First, I don't need a preloader, b/c there is only one image with a rollover and it is the submit button. Secondly, my images are using names like 'login.gif' & 'loginover.gif' vs. 'login_on.gif' & 'login_off.gif'. So I want to see if this is part of my problem.

TIA,
Brian

login or register to post comments

RE: Thank you SIR, May I have another...

Submitted by Jeff Howden on July 21, 2002 - 14:57.

Brian,

Can you send me a link to a page where I can view working code?

There is working code at the URL in my previous post. The example is up at the top of the page.

I have serveral questions which I could only ask if in person. First, I don't need a preloader, b/c there is only one image with a rollover and it is the submit button.

The preLoad() function is useful even if there's only one image and it's rollover state to load.

Secondly, my images are using names like 'login.gif' & 'loginover.gif' vs. 'login_on.gif' & 'login_off.gif'. So I want to see if this is part of my problem.

To get it all working, you'll need to either rename your images, or call the rollOver() function differently from the onmouseover and onmouseout event handlers. I would suggest changing the name of your images so it's more obvious which state they are by their filename.

Good luck,

.jeff

login or register to post comments

Middle Ground

Submitted by pixelmech on August 19, 2002 - 17:37.

I like the article. I think the argument that the folks who are disabling JS are probably not your consumers, or target audience is faulty - with just a hint of truth in it. In reality, you really have to pore over your own logs and get as close to your own users as possible to see what is best for your site. I think a rollover submit button can be nice, done correctly. Just make sure you use the right functionality with it as jeff suggests. I totally agree on the dropdown/go button too. And its used waaaaaayyy to much. Tom

login or register to post comments

minimize user errors with instructions

Submitted by IanO on September 3, 2002 - 13:53.

First let me thank you for having your
{
} aligned vertically. Second let me say that my perspective is as an intranet developer who has fewer problems with the choice of browers. I do like your architecture validateForm(this) because I can construct validateFormOne(this) and validateFormTwo(this) etc.

Now let me rant and rave about forms that give us no clue so we (as users) make errors. The first one is choosing a password, only to find out from the error message that the mimimum length was eight (8) characters. If it had been on the form, I would have given them eight characters originally. Next is required and optional fields; it is important to tell the user which are required before the form is submitted.

Next issue is how to indicate the errors. The method I have used, albeit from the server w/o JavaScript, is to redisplay the original form with some text in red (like an asterick character) and a message to fix those fields. I really hate when I am told to go back and none of my entered data is available to be changed.

login or register to post comments

Would this Validate?

Submitted by factotum on November 1, 2002 - 10:57.

Nice article, thanks for writing it. No reason not to do it this way... But I have a question about your use of <u></u> with what appears to be xhtml tags. Would this work/validate? Does that open up a can of worms in any browsers? I assume you'd need an xhtml doctype... Anyway, thanks for taking the time to put this stuff down.

-factotum

login or register to post comments

Re: Would this Validate?

Submitted by Jeff Howden on November 1, 2002 - 12:01.

factotum,

Nice article, thanks for writing it. No reason not to do it this way... But I have a question about your use of with what appears to be xhtml tags. Would this work/validate? Does that open up a can of worms in any browsers? I assume you'd need an xhtml doctype... Anyway, thanks for taking the time to put this stuff down.

I was pretty sure it'd validate so I just ran an xhtml site I did that uses <u></u> tags to identify accesskeys for form fields and it validated just fine. You also shouldn't experience any browser problems for the <u></u> tags as they were part of the HTML 2.0 spec.

The interesting bit is that while older browsers will see the underlined characters in the form input labels, they don't support accesskeys so the underlined indicators would be rather pointless. <wondering to="self">Hmmmm, maybe it's time someone wrote a bit of script that'd parse the forms on a page and alter input labels that existed where the associated input contained an accesskey attribute/value wrapping the appropriate first letter the script finds in the label with <u></u> tags.</wondering>

.jeff

login or register to post comments

Wondering With You

Submitted by factotum on November 1, 2002 - 12:19.

Ah, but you'd have to check to make sure that two labels didn't start with the same first letter, or match the first instance of the access key value... can it be done? BUM-bum BUM-bum BUM!

I thought for sure an xhtml validator would through a hissy w/ the deprecated underline tags. Good to know it doesn't... figment88 should be happy. Thanks for the reply.

-factotum

login or register to post comments

Re: Wondering With You

Submitted by Jeff Howden on November 1, 2002 - 12:40.

factotum,

Ah, but you'd have to check to make sure that two labels didn't start with the same first letter, or match the first instance of the access key value... can it be done? BUM-bum BUM-bum BUM!

It really wouldn't be all the difficult. The hardest part would be getting it cross-browser so it'd work on both IE6 and the mound 'o Mozilla multiples.

I thought for sure an xhtml validator would through a hissy w/ the deprecated underline tags. Good to know it doesn't... figment88 should be happy. Thanks for the reply.

I double-checked since you mentioned the word "deprecated" and I was using an XHTML Transitional Doctype on the page I validated earlier without problems. When I manually switched the Doctype to XHTML Strict it threw errors for the use of the <u></u> tags. That's a bummer that they're deprecated cause this is a perfectly valid use for them. Oh well. I guess that leaves us with <span> — the gateway tagsm.

.jeff

login or register to post comments

Good Stuff

Submitted by Sh0t on November 2, 2002 - 11:46.

Great article. Man I love this site, I wonder how i went so long without knowing about it?

login or register to post comments

oh well

Submitted by holisticbeatz on November 3, 2002 - 04:02.

i like javascripts, so i use it. however, thats all there is to it. yes it can be rather infuriating to the non-javascript user. oh well.

login or register to post comments

Very good!

Submitted by ravi on March 31, 2003 - 17:16.


Excellent article!
Especially the rollover thingy has always been too much of a compromise to be actually involved in a specific project.

Greets,
ravi

login or register to post comments

rollovers and more

Submitted by mswitzer on April 16, 2003 - 09:49.

first, you don't need a preloader if you define a .src for an image in javascript - i can't think of a regularly used browser that doesn't support javascript 1.1 which automatically loads all .src even if it's not to be displayed immediately... it may not seem to be a big deal, but when you are looking at optimizing a site, including the preloader actually loads the image TWICE

second, in reference to the comment about saying what data should be entered into the field prior to user entry, I find filling the field with the default value works great - then using javascript to clear it when it's focused (yes I know it doesn't work in js-turned-off browsers but it's still functional) is a plus...

for instance: Password:

Or you can simply put in parentheses below the field the requirmeents for the input... ;-)

login or register to post comments

form example

Submitted by mswitzer on April 16, 2003 - 09:54.

ugh - the form example appeared in the preview, but not here :(

login or register to post comments

RE: rollovers and more

Submitted by Jeff Howden on April 16, 2003 - 11:29.

Michael,

First, your claim that preloading is unnecessary because any reference to .src will result in the browser automatically loading the image is false. The only time the browser will load the image is when you're executing script that sets the .src property of an image object. If the statement is within an event handler like onmouseover or onmouseout then there will be a slight delay in executing that statement as the browser must first download the image if it hasn't already been loaded. Preloading the image eliminates the pause as the image is then already in memory.

Second, the penalty you cite for preloading an image doesn't exist. When the browser encounters an object with the same path as an object that's already been downloaded/cached it checks to see if the modified date is different and if not uses the version from the cache or in memory. If this wasn't the case then those pages that use hundreds of instances of a single-pixel gif as a spacer image in the layout would generate hundreds of requests to the server for the same file. However, that's not how web browsers work. So, your claim that the image is loaded twice from the server is completely false.

Thanks,

.jeff

login or register to post comments

RE: rollovers and more

Submitted by mswitzer on April 16, 2003 - 11:58.

actually as long as reference to the .src is in the head of the file it will preload... per javascript 1.1

and second the penalty does exist if you are referring to the same image differently in your javascript... it's not the same as when an img tag is used in html.

FYI

var ug1 = new Image()
ugh1.src = 'image.gif' // loads once

var ug2 = new Image()
ugh2.src = 'image.gif' // loads again

I understand browser cache, a simple way for you to see what I am referring to is if you are running Netscape 7.0 on any machine, use the View Info and then use the Media tab - go through the images many of them will be the same filename, but not all will have Disk Cache as the Source.... even multiple instances of the same image will have (not cached) in the source

at least this is what I've found from my experiences

thanks

login or register to post comments

RE: rollovers and more

Submitted by Jeff Howden on April 16, 2003 - 13:33.

Michael,

actually as long as reference to the .src is in the head of the file it will preload... per javascript 1.1

That statement, in its simplicity, is not totally true. If the reference is within a function then the loading of that image will not happen until that function is called.

and second the penalty does exist if you are referring to the same image differently in your javascript... it's not the same as when an img tag is used in html.

Again, your assumption is incorrect — at least as far as competent browsers are concerned. The browser compares full paths and the modified data on the cached resource, if it exists. If it doesn't exist in the cache or the modified date is newer, it will request another copy. It does not matter if the same image is referenced multiple times, the paths seem different, or anything. Any competent browser will only load the file from the server one time.

Here's an example of the headers from little exercise you posted:

GET /images/t.gif HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
If-Modified-Since: Sat, 12 Apr 2003 19:40:30 GMT
If-None-Match: "7eaa1c602b1c31:88f"
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
Host: jeffhowden.com
Connection: Keep-Alive

HTTP/1.1 304 Not Modified
Server: Microsoft-IIS/5.0
Date: Wed, 16 Apr 2003 20:48:33 GMT
X-Powered-By: Jeff Howden (http://jeffhowden.com)
ETag: "7eaa1c602b1c31:890"
Content-Length: 0

I already had the file I referenced in my cache. So, it didn't even make a connection to the server for it.

I understand browser cache, a simple way for you to see what I am referring to is if you are running Netscape 7.0 on any machine, use the View Info and then use the Media tab - go through the images many of them will be the same filename, but not all will have Disk Cache as the Source.... even multiple instances of the same image will have (not cached) in the source

Obviously Netscape 7.0 (probably all Mozilla variants/derivatives actually) are incompetent when it comes to how external resources are managed. The behavior you cite is a bug, not a feature, and should not be considered standard behavior and should definitely not be coded for.

Thanks,

.jeff

login or register to post comments

RE: rollovers

Submitted by mswitzer on April 18, 2003 - 05:04.

>>at least as far as competent browsers are concerned ... the behavior you cite is a bug, not a feature

guess I can't argue with that logic :)

>>If the reference is within a function then the
>>loading of that image will not happen until that function is called.

true - but when you setup your vars:

var imageOne = new Image()
imageOne.src = "images/buttonOne.gif";

- that in itself tells the browser to load the image...

as long as you set up your mouseover buttons as vars in the head you can reference them by "name" without having to preload them... I think I know what you are referring to - when people do>

but if you set up your mouseover images as vars in your head, you don't need to go ahead and preload them via another function as well... since your vars are not within a function but still wthin script tags, the browser doesn't need to wait until a function is called...

does all that seem to make more sense?

login or register to post comments

RE: rollovers

Submitted by Jeff Howden on April 18, 2003 - 11:01.

Michael,

true - but when you setup your vars:

var imageOne = new Image()
imageOne.src = "images/buttonOne.gif";

- that in itself tells the browser to load the image...

IYes, we're in agreement on that. If you're going to take the time to write those two lines of code (and it's usually more like those two lines of code times the number of images you can swap in the design), then why not just use a preloader?

as long as you set up your mouseover buttons as vars in the head you can reference them by "name" without having to preload them [...]

Have you taken a look at the preload 'n rollover scripts that were mentioned further up i n these comments? When you do, you'll notice that this is exactly how they work.

[...] I think I know what you are referring to - when people do onMouseOver="document.imageName.src='images/buttonOne.gif'" - that image doesn't load until the mouse pointer goes over the event trigger

Yes, that's exactly what I'm referring to. There are a myriad of reasons to not use that syntax. Probably the most important is to avoid throwing errors for browsers that don't support JavaScript 1.1. Sure, the number is quite small, but those errors are unnecessary, unprofessional, and could make the site completely unusable.

but if you set up your mouseover images as vars in your head, you don't need to go ahead and preload them via another function as well... [...]

Well duh. I don't think I ever said that you should define them manually and preload them with a function. In fact, I think what's being said is that you should pick one or the other, but not for the reasons you cite.

[...] since your vars are not within a function but still wthin script tags, the browser doesn't need to wait until a function is called...

And you don't necessarily have to design your preloading setup to wait for an event like onload in order to start the preloading. you could just as easily have the preload function fire in the head of the document.

Why do I get the feeling we've been saying the same thing the entire time?

.jeff

login or register to post comments

talking around each other

Submitted by mswitzer on April 18, 2003 - 11:15.

same message - different language - happens all the time LOL!

but yeah - i think we're saying the same thing... i briefly looked at the link above and it all makes sense to me, I use a similar function for my rollover, just don't include the state within my function. I set up vars for the on and off images (which as we discussed preloads them) and then change the src to the different vars src....

your function basically does the same thing, I think in less steps... pretty nice!

login or register to post comments

Mercedes Benz website doesn't like Opera 7.11!!!

Submitted by dusoft on May 30, 2003 - 05:41.

You are using Opera 7.11 In order to view the online Mercedes Experience, either Netscape 6.2 or above or Internet Explorer 5.x or above is required. We recommend you update your browser by following the links below. Choose a recommended browser: Microsoft Internet Explorer for Windows Microsoft Internet Explorer for Macintosh Netscape Drag the following link to your desktop: Visit MBUSA.com. Once you've updated your browser, you can follow the link from your desktop directly to MBUSA.com.

login or register to post comments

MBUSA.com

Submitted by Jeff Howden on May 30, 2003 - 07:41.

I noticed today that the problem I noted in this article has been addressed. It no longer has the rollover effect and has been dummied down to a basic submit button. If you view the source, however, you still see the HTML from the original button. I can only hope that this article was read by someone there and that prompted some change. For those interested, here's a snippet of the HTML:

<!--
  <a href="javascript:submitLocatorForm1();"
     onclick="return validateForm(document.forms[0]);"
     onmouseover="swapImg('button_submit_0','/media/images/main/locator/button_submit_0_1.gif');"
     onmouseout="swapImg('button_submit_0','/media/images/main/locator/button_submit_0_0.gif');"
  ><img src="/media/images/main/locator/button_submit_0_0.gif"
     width="60" height="13" alt="" border="0" name="button_submit_0"
   /></a><br />
-->
<button type="submit">Submit</button>

Someone there still needs to take a lesson in HTML & Browser Compatibilities because they opted to use the &lt;button&gt; tag to render a button rather than a standard &lt;input type=&quot;submit&quot;&gt;. Oh well, maybe this comment will spur some more action.

.jeff

login or register to post comments

Superb article

Submitted by janet on October 30, 2003 - 04:07.

There's a reason for this one being the highest rated article here.

login or register to post comments

Chevrolet.com. It's Fixed

Submitted by thew on August 20, 2004 - 21:25.

I love evolt and this post has plaqued me ever since I first saw it. My team and I have just finished the 2005 Chevrolet Redesign. We did it in valid XHTML 1.0 Strict, CSS, semantic markup, and its accessible. With regards to the form validation with JavaScript, check out the contact us forms on Chevrolet.com. I've found a way to have an accessible form with a validation routine that can be dropped into any page with little or no customization to the script.

Ok, now I have closure.

Thanks everyone,
Matt

login or register to post comments

Fixed, but is it SEO Friendly?

Submitted by Brad Henry on December 20, 2006 - 16:38.

Since this comment is fairly new on this old post, it looks like their has been another redesign since the previous post about it being fixed. I am commenting on the newest redesign. It looks like Chevrolet is using sifr which is one of the newest ways to inject text into what previously wasn't SEO friendly such as flash. This somewhat new technique of using javascript to inject xml into objects is very effective and I first noticed it with the Pontiac.com website. Typically it is just used for titles but can also be used for whole sections of text. However, I can't find in the code exactly where it is being used, but I can tell it is because of the Javascript file that is called sifr. Anyways, I just wanted to complement the use of sifr in the new design!
Thanks,
Brad Henry

login or register to post comments

cheers

Submitted by yahmaster on January 10, 2007 - 00:09.

Amazing stuff, and a great article, great topic. Thanks

login or register to post comments

"Accessibility is also a

Submitted by cianuro on January 13, 2007 - 12:43.

"Accessibility is also a major issue with Ajax technology, many websites are using it for validating their forms, but as the article says anything based on JavaScript is inaccessible when no alternative solution is provided for non JavaScript users." If you take a look at Online Marketing Ireland all the javascript we use has an alternative for users with javascript turned off.

login or register to post comments

minimal of use

Submitted by chulian on January 20, 2007 - 16:18.

i try to avoid java script as far it is possible. in general you get into troubles with users an search engines. with a knowly use you can use javascript e.g. to hide specific areas or links form search engines. i some cases it is really helpful to do this if you dont't want that some areas of our domain or on pages should not get into the index of a search engine. i've did it for example on my finca page. but for links you should keep in mind that google is able to follow non masked javascript links.

login or register to post comments

Yes it's been a while since

Submitted by cindy25 on March 19, 2007 - 23:55.

Yes it's been a while since googlebot and probably slurp are able to follow java links. Not only nonmasked but also the ones that are masked. However I can't say that I've tested this.

login or register to post comments

older browsers

Submitted by tophatsolutions on March 29, 2007 - 18:09.

I agree yes the interesting bit is that while the older browsers will see the underlined characters in the form input labels, they don't support accesskeys so the underlined are useless. Stephen

login or register to post comments

a problem when using in shops

Submitted by AxelF on April 2, 2007 - 05:18.

My experience is: never require that the user has javascript enabled, especially in money-forms like checkout carts of online shops. Its a better way to make the necessary checks with a serverside language like PHP. Axel

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.