Archive for the ‘Web Standards’ Category

Don’t do this: Initially visible ‘loading’ images

Sunday, October 10th, 2010

A common pattern on interactive web sites is to include a ‘loading’ image (sometimes called a ‘throbber‘), and display the image when an asynchronous action is taking place. This is usually implemented by placing an animated GIF inside a div that is initially hidden, and is displayed by JavaScript that is executed when the action begins.

However, bad things can happen when you do not initially hide the loading image using CSS. I’m an advocate of using NoScript to block JavaScript execution on untrusted sites, and I found a site that had a working throbber in my face while trying to read a blog post. Because NoScript blocked the JavaScript execution, the code that initialized the loading image by hiding it never executed, and the annoying circular ’spinning wheel’ made me move on without reading the post.

The way it should work:

  1. Set the initial style of the loading image <div> to include display: none;
  2. When the action starts, modify the <div>’s style to display: block;
  3. When the action ends, return to display: none;

Penny-wise, pound-foolish development decisions

Saturday, August 7th, 2010

Benjamin FranklinRecently, I was reading “Reductionism in Web Design“, which was generally a good “less is more” article that touched on reducing content, code and design down to their minimums without sacrificing quality.

However, there was one guideline in the article about code reduction that made me think twice:

Try to write code natively before using an abstracted layer (like MooTools or jQuery)

This really depends upon what it is you’re trying to reduce: the total size of the application code, or the size of YOUR code? The whole point of code frameworks is to allow you to do more while writing less code. Since you spend less time reinventing the wheel, you can complete coding quicker, and with higher quality (since you’re using somebody else’s tested code).

This is particularly true with jQuery, especially when you apply multiple functions on a set of elements. Since jQuery functions return a jQuery object, you can “chain” multiple function calls, which looks something like this:

$(".classname").function1().function2().function3();

In order to do this without jQuery, you’d need to iterate through each element with the class ‘classname’, then iteratively call each function.  If you used jQuery to do this, you would only need to write one line of code, but you’re total application size would increase by including the fully cross-browser tested jQuery library (a whopping 24 kilobytes). If you did this by hand, it would be many more lines of code, the application size would be smaller, and the entire iterative process for calling the multiple functions would require you to expend addition effort testing across multiple browsers.

This may be an application of the penny-wise, pound-foolish pattern: writing code natively may make your total application size smaller, but at the cost of maintainability and testing.

Firefox 4 beta 1: A very quick first look

Thursday, July 22nd, 2010

There’s not much wrong with the first beta release of Firefox. It performs well, never crashed during several days of use, and, thanks to changes in the menu bar, is much better at using available screen real estate.  Unfortunately, it’s not an everyday-use browser. Yet.

It’s the lack of compatible extensions that keep this from being an everday-use browser.  It has become very apparent just how much I use extensions in my day-to-day use of Firefox.  Between Firebug, Greasemonkey, Read It Later and Xmarks, I can’t do more than just review how my sites look and perform in the new browser. The good news is that NoScript and AdBlock Plus *are* available now, so it’s not you’re browsing unprotected.

Most of the changes just take a bit of getting used to. Finding where the menu bar went and how to get there was a bit of a challenge, but, frankly, there aren’t many daily-use things in the menu bar that are not in the Firefox drop down menu.

During the time I used beta 1, I found only one rendering glitch, and that was with the pan control in the aerial view feature of Google Maps. There appeared to be a ‘ghost’ control behind the main control, and as a result, I couldn’t move to a westerly view. Closing the browser and starting over seemed to take care of the problem, though.

It appears as if there are new features still on the horizon; the extensions page says to ‘watch for something new’. And while eliminating dialog boxes was a focus of this release, several still remain, including the error console. An example of where a dialog box went away is the extensions page. Expect to see more of that in the upcoming beta releases.

HTML field hints with progressive enhancement

Monday, January 18th, 2010

Genesis, a progressive rock band (source: thisisbossi/flickr)

Adding “hints” inside input elements has recently come into fashion.  This is achieved by putting helpful instructions inside input elements that disappear when that element receives focus by the user either clicking in the field, or using the tab key to navigate to the field.  I’ve resisted doing this because I found it makes the form “noisy”, and have always preferred using tool tip functionality by using the ‘alt’ tag. Another reason I haven’t used that method is because I’ve never seen an implementation that behaved properly in the absence of JavaScript. This is due to lack of adherence to the principle of “progressive enhancement“. Here, I show how to add these ‘disappearing field hints’ in such as way as to not be obnoxious when browsing without JavaScript.

But who doesn’t use JavaScript in this day and age?

I don’t, sometimes. I use a Firefox extension called “NoScript” that allows only sites that have been whitelisted to execute any JavaScript.  If I visit a site that’s new to me (for example, after doing a Google query or following a link from Twitter), it’s done with JavaScript off until I know the site is safe. So other than my paranoid surfing habits, what other scenarios could involve using a browser without JavaScript? Perhaps a screen reader for those with difficulty seeing (although it’s becoming more likely for screen readers to support JavaScript)? Perhaps a mobile browser that has had JavaScript turned off due to bandwidth restrictions? But the question “Who doesn’t use JavaScript” is beside the point. The principle of progressive enhancement stipulate that your site should remain as coherent as possible when JavaScript (and for that matter, CSS) is turned off.

What happens when using hint text without JavaScript

If I visit a site that uses field hints, something like the following happens:

The ZIP code field for accuweather.com when visiting without JavaScript on, and starting to type in my ZIP code

In the example given, I went to AccuWeather, clicked on the ZIP code field and started to enter my ZIP code. However, the “hint” text didn’t disappear, and my ZIP was embedded inside the hint text.  In situations like this, I end up needing to manually erase all the hint text and then enter what I wanted to search for.  That’s not how it should work. If JavaScript is used to clear the field upon gaining focus, then JavaScript should also be used to populate the hint text. The implementations I’ve looked at appear to set the field’s value attribute manually, meaning that the hint will still appear when JavaScript is off, and will remain there when it gains focus.

My example

I’ll make a very simple example to show how these types of fields should be implemented.  My goals are: 1) To degrade gracefully when JavaScript isn’t available, and 2) Make the hint text look different so that the user can tell the difference between what’s a hint and what is user-entered data. Doing this will also help the implementation of removing the hint when it gains focus; I’ll explain later.  Here’s my sample form:

My simple, base form for this example

And now, the code to create this very simple form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Field hints</title>
</head>
<body>

<form action="#" method="post">
<fieldset>
<label for="search">Search</label>
<input id="search" name="search" type="text" size="40" maxlength="40" value=""/>
<input id="submit" name="submit" value="Search"/>
</fieldset>
</form>

</body>
</html>

Step 1: Styling the hint

In the AccuWeather example above, the hint text looks exactly the same as user-entered text, so the user cannot distinguish between the hints and the data they entered. Some sites use either a different color or style of font (or both), and I like this approach. So the first step will be to create a class style that can be applied to the search field when it’s displaying a hint.  Let’s make the text a light gray and italic. Add the following to your CSS file:

.showhint {
 color: #CCCCCC;
 font-style: italic;
 }

Any field in your form will need to have the class “showhint” assigned to it as a part of the page setup.  Do not, under any circumstances, set this class in the HTML. To support progressive enhancement, we need to separate content and actions; let JavaScript take care of setting and unsetting the class for this element.

Make the hint text color dark enough to be read, but light enough to really make it stand out from the rest of the text in your form.  When the field gets focus, this style will be removed, and the field will revert back to the standard styles inherited from the form.

Step 2: Adding the jQuery ready handler

I’ll use jQuery in this example, but just about any JavaScript framework will be able to handle this. Code passed to the jQuery’s ready function will be executed once the page has been fully loaded. This code will be responsible for setting the hint style to the search field, as well as setting up the hint:

<script type="text/javascript" src="./js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
 $(document).ready(function() {
   $("#search").attr("class", "showhint");
   $("#search").val("Enter search terms here");
});
//]]>
</script>

Note that the first line includes the jQuery script.  Without that, all the $() calls would fail. This code will execute only if JavaScript is enabled.  If JavaScript is not enabled, the style will remain the same, and the hint text will not be added; all the user will see is a blank search field, which they can start entering search text without needing to manually clearing the field themselves.

Step 3: Handling gaining focus

The rule is that the hint text should disappear when the field gains focus if the hint text is present. That last clause is there to prevent any user-entered data from getting wiped in the event the user clicks on or tabs to the search field again. In other words, just clearing the search field every time it gains focus will not solve the problem.  In the example, the hint text is “Enter search terms here”, so on focus, all we need to do is check if the search field’s value is “Enter search terms here”, and clear it if it is, right? Well,consider what would happen if the user was actually searching for “Enter search terms here”. Unlikely yes, but determining if the hint is being displayed based upon the value of the field just isn’t the right thing to do.

Remember earlier when I said that applying a class to the input field will help out with the implementation of removing the hint text? This is where I explain why. Instead of looking at the content of the field, look at the class of the field. If the class is “showhint”, then it’s in “hint mode”, and we should reset the text and class. Create a focus handler for the search field that will look at the field’s class, and if it’s in hint mode, remove the hint text and the class, causing the field to become blank, and inherit the form’s styles:

$("#search").focus(function() {
 var className = $("#search").attr("class");
 if (className == "showhint") {
   $("#search").val("");
   $("#search").attr("class", "");
 }
 });

That basically completes our task. A user with JavaScript will see the hint, and the hint will disappear when the field gains focus. A user without JavaScript will see a blank field. But if we really wanted to get fancy, we could reset the search field back to hint mode if the user didn’t enter anything into the field:

$("#search").blur(function() {
 if ($("#search").val().length == 0) {
   $("#search").attr("class", "showhint");
   $("#search").val("Enter search terms here");
 }
 });

So if a user tabbed into a field with a hint, then didn’t enter anything before tabbing into the next field, the hint text in field would reappear.

What good will this do if my form submit requires JavaScript?

I’d first reconsider why your form would *need* JavaScript. The most likely reason is validation, but you shouldn’t depend solely on JavaScript validation before taking action on a request; there should be some additional validation going on in the back end (server side) code. But, for whatever reason, you absolutely, positively need JavaScript, note it in an <noscript> block that displays at the top of the page so the user knows you need JavaScript to use the page. Given the above search field example, if JavaScript was required to fire off the search, then perhaps the search HTML should be hidden from those without JavaScript.

Examples

Do NOT click that button!

Tuesday, January 5th, 2010

star5112 / flickr

Ever click on a button, decide you’re doing the wrong thing, and then move the mouse outside the button? I have, and when it’s implemented incorrectly, it drives me nuts.  It’s all due to using the JavaScript events onMouseDown and onClick incorrectly.

The button that won’t unclick: onMouseDown

Accidentally click the button below (click inside the button, then realize the horror of doing it, and then try to drag out of the button area):

This kind of button implementation annoys the crap out of me. There’s nothing you can do if you accidentally click the button, because by the time you realized you made a mistake, action already started. That’s because the button’s action is triggered by an onMouseDown event. Regardless of what happens next, that event is going to fire. So you cannot “cancel” the action by dragging the mouse out of the button and releasing the mouse button. The event has already fired and the action already started.

There’s a similar issue with the iPhone implementation of buttons. If you tap a button, but do not release, and drag out of the button, the button’s action will fire when you move outside the button. What’s interesting about this is that I cannot duplicate that scenario with a web browser. It appears that a onMouseUp event for a button is fired only if the mouse is still within the button, even if the corresponding onMouseDown event was inside the button.

The button that will click when it shouldn’t: onMouseUp

So that means it’s OK to use onMouseUp to trigger actions when a button is clicked, right? NO! With the button below, click outside the button, then drag to an area inside the button, and let the mouse button go:

The right way: onClick

While less annoying than the original button, it’s not correct behavior. A button should only have it’s action triggered if the mouse button is pressed and released within that button. That’s the onClick event, as implemented by this button.

Do both of the prior tests with this button. The only time you’ll see an alert is if you press the mouse button down, and then release it while inside the button. In fact, you can click inside the button, drag outside of it, drag back in, and then release the mouse button, and it will still work.

This is how your buttons should look in HTML:

<input type="button" value="Edit" onclick="javascript:theAction();"/>

Doing this means your buttons won’t fire too early. Also note that this isn’t an issue when using “submit” type buttons, as their behavior is automatically onClick.

You forgot to include kitchensink.com

Tuesday, December 1st, 2009

Sometimes strange things catch my attention. As a web professional, sometimes web sites acting strangely catch my attention.  Over the last couple of days, two different sites did things that not only caught my attention, but completely blew my mind. And not in the good way.

One of the sites (which will remain nameless) is a tech blog I normally read via RSS, but I found myself actually reading from the site recently.  As I did, I noticed the status bar flickering, and the load progress bar not quite all the way to the end.  The page was obviously still loading, but it appeared that the page was complete.  As I scrolled down the page, I noticed that the blogroll used the favicon of each blog listed in a very long list.  Because I do not visit many of the sites on that blogroll (apparently), my browser had to go to each site and download the favicon for each blog. The good news about that is now that I’ve fully downloaded the page, I have all those favicons cached, and subsequent loads of that page should be snappy, but I have to wonder if there isn’t a better way to do that.

It could be possible to put all the favicons into a sprite image, and download the single image file and let the browser’s CSS do it’s magic.  However, there are (at least) two things wrong with doing that.  First, if the blog’s owner decides to change the favicon, the incorrect icon will appear in the blogroll until the sprite image is updated. Second, copying somebody else’s graphic handiwork onto your server is ethically shady. Ethically, the blog’s designer did the right thing and reference the favicon from each of the remote sites. Unfortunately, the ethical thing to do was not the speediest thing to do. In this case, the blog’s designer would have to ask the question “does including the favicon from each of these remote blogs add any value worth the hit in performance?”  In my mind, the answer would probably be no.too-many-includes

The first attention-grabbing site was a personal blog site.  The second, however, is a high-traffic tech news site (which will also remain unnamed). This site is big into embedding JavaScript or Flash from other sites on their page.  The reason I know this is because I use a Firefox extension called No Script that blocks all JavaScript and Flash content unless I have explicitly allow a given hostname.  The image to the right is the No Script status bar. Note the number of sites. That’s a lot. (An aside: The sites with the blue S icon are those that I have not allowed to load, and the sites with the red circle and slash through them are being allowed.) Many of the includes are for site tracking or commenting, but in my mind, there are way too many includes here.  All of these things take time to load.  This, too, would be another one of those situations where the site’s designer has to ask if the value added by all these includes is worth the extra time it takes to load the site.

This same site doesn’t come close to having well-formed HTML, either.  Below is the output of HTML Validator, showing not just a large number of errors, but several frames as well.  I had thought frames died in 1999. Apparently not.

too-many-errors

Pay attention! I don’t say this often: “Microsoft, I love you!”

Monday, November 30th, 2009

Simply put, even Microsoft is encouraging people to stop using IE6. And on International Blue Beanie Day, too!

Source: mashable.com

Source: mashable.com

Enforcing XHTML tags in a JSP template

Tuesday, September 15th, 2009
For those of you that don’t know me, and most of you don’t, I’m a very compliance-based person. I love standards and writing code to meet or exceed those standards. In the world of web development, we have a great set of standards that detail how web pages must be laid out, and we even have excellent free tools to ensure that our HTML, regardless of how it’s generated, is compliant to the W3C standards.

Imagine my horror when I ran a validation check against a JSP/Struts project using XHTML, and found that it failed. I still tear up a bit when I think about it. There were several failures of certain tags not being properly closed. To make debugging matters worse, not all tags were exhibiting this problem.

The problem centered around <input> tags not being properly terminated. In XHTML, all tags, including those that do not have body contents, must be closed. A tag without a body should close itself (i.e. <input />). Looking at the generated HTML source, I could see that tags generated by the Struts html taglib weren’t being closed.

Typically this means that the page was not declared as XHTML; this is done by using the <html:html> tag with the xhtml attribute set to true. I looked at the JSP, and confirmed that the xhtml attribute was in fact set. When that attribute is set, the Struts taglibs are supposed to create XHTML-compliant code. In this case, it was not doing that.

I started looking around various Java and Struts web sites, looking for people having the same issue. If I did find a similar issue, it was due to a defect in very early releases of Struts, and was not applicable to the release I was using. I then started looking at the Struts html taglib documentation to see if I was using the <html:html> tag correctly, when I found the documentation for a similar tag, <html:xhtml>, which contained this pearl of wisdom:

Using this tag in a page tells all other html taglib tags to render themselves as XHTML 1.0. This is useful when composing pages with JSP includes or Tiles.

Not only am I compliant, I’m big on code reuse, which means using templates that use the aforementioned JSP includes. It turns out that the <html:html xhtml=”true”> tag does not apply to JSP’s that are included. To fix the problem, the <html:xhtml/> tag had to be placed at the start of all included files.

Then compliance nirvana began.