Use of aria-describedby with form elements that have descriptor text

If form fields have formatting help or descriptor information for the input, such as “Passwords must be 8 characters long”, one cannot assume that screen readers are reading that input by default.

<label for="choosePassword">Choose Password:</label>
<input id="choosePassword">
<span class="help">Passwords must be 8 characters long</span>

When users tab through the form, and focus to this field is reached, assistive technology such will say “tab Choose Password colon edit” (JAWS, in this case, with verbosity settings set to advanced). This user is completely missing out on needed information to fill out the form field.

For a screen reader to read the help text, one can address this gap in one of two ways. One way is to incorporate the extra text as part of the label:

<label for="choosePassword">
    Choose Password:
    <span class="help">Passwords must be 8 characters long</span>
</label>
<input id="choosePassword">

For some web designers this is perfectly fine. They will nest the descriptor text within the label, and leave it there, or perhaps use CSS to position that element elsewhere. Screen readers will read the descriptor text just as it normally would read the label.

The second way is to use the aria-describedby attribute:

<label for="choosePassword">Choose Password:</label>
<input id="choosePassword" aria-describedby="choosePasswordHelp">
<span class="help" id="choosePasswordHelp">Passwords must be 8 characters long</span>

The aria-describedby attribute value should match the id of the descriptor text. JAWS will read the above as “tab Choose Password colon edit Passwords must be 8 characters long”.

Using aria-describedby much less intrusive on your HTML than nesting potentially long descriptor text into the label, as it’s merely the introduction of an attribute on existing markup. The downside is that not all assistive technologies necessarily support aria attributes. In this case, the JAWS screen reader and VoiceOver do support aria-describedby, and that’s enough for me to adopt aria-describedby as part of my regular practice. (NVDA does not support it as of this writing according to my tests, and I don’t know about Window-Eyes and other technologies.).

Even more uses

aria-describedby need not be limited to one value, but instead it allows a space-delimited set of values (like the class attribute). This can come in handy in the instance that there are errors related to a field in question.

<p id="error_choosePassword" class="error">Error: Please enter a valid password.</p>
...
<label for="choosePassword">Choose Password:</label>
<input id="choosePassword" aria-describedby="error_choosePassword choosePasswordHelp">
<span class="help" id="choosePasswordHelp">Passwords must be 8 characters long</span>

Now when focus is put on the text field, JAWS will say “tab Choose Password colon edit Error colon Please enter a valid password. Passwords must be 8 characters long”.

Getting around the flicker of JavaScript modifying the DOM while the page is loading

When building things with progressive enhancement, I often want the page styled a certain way when JavaScript is on vs off. When you use $(document).ready() in order to modify your page, you may end up watching the page modify before your very eyes, and if you’re like me, wish you could find a way around it.

For instance, I might have portions of a form hidden by default unless the user clicks an option to expand it. My old method was to show it all by default, then using $(document).ready(), hide those options. The problem is that I would see a flicker as elements start appearing then disappearing on my screen.

Now I use this method:

<body class="nojs">
    <script>
      var bodyEl = document.getElementsByTagName('body');
      bodyEl[0].className = bodyEl[0].className.split('nojs').join(' jsEnabled ');
    </script>
    ...
</body>

So by default, my page has a nojs class. And a script runs immediately after to remove that class, and to add in a ‘jsEnabled’ class in its place. I can then do things in my stylesheet like this:

.conditionalContent { display:none; } // what I really want to happen
.nojs .conditionalContent { display:block; } // in case JS is disabled

This accomplishes the same thing as I was trying to do above (keep an element hidden by default if JavaScript is disabled, but show it by default if JavaScript is disabled) but without the flicker.

And then you also have an option to make use of .jsEnabled class in the stylesheet as well.

If you happen to have jQuery pulled into your site in your <head>, you can use this instead:

<body class="nojs">
    <script>
      $('body').removeClass('nojs').addClass('jsEnabled');
    </script>
    ...
</body>

If anyone’s discovered other methods of getting around this type of issue (like using Modernizr, or something else), I’d love to hear about it.

CSS gradients and background images

Let’s say you have a web page with a solid pale blue background color with a background image positioned on top of it.

body { background: #a5c9e5 url(img.png) no-repeat 50% 300px; }

And this is the result:

See example 1 HTML.

Then you heard about CSS3 gradients and thought, “Wow! Now instead of a solid pale blue in the background, I can have a dark blue to pale blue fade!”

With this line of thinking, one may think that taking the ‘background-color’ value part of the shorthand above (‘#a5c9e5′), and replacing it with a ‘linear-gradient’ property would do the trick:

body { background: linear-gradient(top, #1e5799 0%,#a5c9e5 100%) url(img.png) no-repeat 50% 300px; }

But that’s not how it works. Despite the fact that you can define them using hexadecimal, rgb, or rgba, CSS background gradients are not like background colors, but instead are like background images.

So to get effect we described above on the same element, our browser would need to support multiple backgrounds, and we’d need to declare it like so.

body {
	background:
		linear-gradient(top, #1e5799 0%,#a5c9e5 100%),
		url(img.png) no-repeat 50% 300px;
}

(Note: For the sake of simplicity, this example CSS is simplified without all the additional declarations that use vendor prefixes.)

But when testing that out, we only see the gradient.

See example 2 HTML

Where’s the background image? It’s there, but under the gradient. The order in which the background images are specified matters. If we rearrange the properties so that the image is first and the gradient is second:

body {
	background:
		url(img.png) no-repeat 50% 300px,
		linear-gradient(top, #1e5799 0%,#a5c9e5 100%);
}

The image will show up as desired – on top of the gradient.

See example 3 HTML.

Think of CSS gradients not as a color, but as images. The guidelines for combining multiple background images apply to CSS gradients, too.

Resources

Source of train picture.

Nudging elements with position: relative

I find that most people are familiar with using position: relative; on a containing element so that its descendent can be absolutely positioned relative to that element. So to get this effect:

The positioning rules would look something like this:

.container {
	position: relative;
}
.container div {
	position: absolute;
	top: 20px;
	right: 20px;
}

Relative positioning is also helpful for positioning the targeted element relative to its expected position in normal flow.

Let’s say I have an image in my document:

<p>This is a paragraph</p>
<img src="img.png" alt="A man on a bycicle" />
<p>This is a paragraph</p>

By default, the markup above looks like this (see example 1 html):

But I’d like it to be pulled out a little for a magazine-like look. I’ll start by adding float:left; to the image so that my text can wrap around the image.

.container img { float: left; }

That will get me this (or see example 2 html):

But I want to pull the image off to the left so part of it is visually extending outside the article. I’ll specify 100 pixels to the left, but first I have to specify position:relative;.

.container img {
	float: left;
	position:relative;
	left:-100px;
}

Resulting in this (or see example 3 html):

Hmmm… but the text is continuing to wrap around the image as if it’s still in its original spot.

That’s relative positioning — the element can be visually offset from its position in the normal flow, but the browser reserves that element’s original space. In order to have our text flow around the image’s new position, we can use negative margins. Since I don’t want the text butting up against my image, I’ll just use 80 pixels instead of 100 pixels, which allows a 20 pixel gutter between the image and text.

.container img {
	float: left;
	position:relative;
	left:-100px;
	margin-right: -80px;
}

Resulting in our desired result (or see example 4 html):

Relative positioning is helpful for not just setting a context for the absolutely positioned elements within them, but can also allow more flexible positioning opportunities. Though this article only covered an example for pulling items left or right, the concept can also be applied to vertical offsets (top and bottom). In conjunction with negative margins, relative positioning can help some designs ‘break out of the box’ allowing elements to extend outside their normal containers.

Waqas asks the CSS Guy how to specify an alternate font size if the preferred font isn’t available on the user’s system

Waqas writes:

Is there any way to specify alternate font size?

e.g.

p { font: 11px Tahoma, Helvetica; }

If Tahoma font is not available in machine, Helvetica will be used (if available) with size 11px. Is there any workaround that if Tahoma is available it will use size 11px & if it is not available Helvetica will use for example 13px?

Yes – here’s a way. I had found this article from 2007: JavaScript/CSS Font Detector, so let’s use that as a starting point.

I’ll start with HTML for a simple paragraph:

<p>Row, row, row your boat<br />
Gently down the stream.<br />
Merrily, merrily, merrily, merrily<br />
Life is butter dreams.</p>

And style it:

<style type="text/css">
p { font: normal 28px/1.2 'Brush Script Std',Arial,sans-serif; }
</style>

And so I have two fonts: Brush Script Std as my preferred font, and Arial as my fallback. The challenge is that supposing Brush Script Std isn’t on the user’s system, I want Arial to display not at 28px, but at 18px.

I’d approach is like this. First set a style rule for the fallback state. If we know that ‘Brush Script Std’ is available, let’s use JavaScript to add a class to the body tag that indicates the font is good to use, like <body class="hasBrushScriptStd">. I could then write a separate style rule that makes use of that selector, like so:

<style type="text/css">
p { font: normal 18px/1.2 Arial,sans-serif; }
.hasBrushScriptStd p { font: normal 28px/1.2 'Brush Script Std'; } 
</style>

Now for the script that handles the font detection and adding of the class name to the body. I verified that Waqas isn’t using jQuery, so I’m writing a couple of extra functions to handle the onload event and the adding of class names. (credits at the end of the article).

<script type="text/javascript" src="fontdetect.js"></script>
<script type="text/javascript">
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
function addClass(element,value) {
  if (!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}
addLoadEvent(function() {
  var detective = new Detector();
  var hasBrushScriptStd = detective.test('Brush Script Std');
  if (hasBrushScriptStd == true) { 
    addClass(document.getElementsByTagName('body')[0],'hasBrushScriptStd');
  }
});
</script>

Here’s the final result where you can view source and copy if you wish. Know of other methods, better methods, or gotchas? Tell me about it.

Script credits:

Memphis AIGA Mini-conference

This saturday morning, October 16th, there is a local AIGA mini-conference on topics like designing for mobile, HTML5 and CSS3 (yours truly speaking), HTML frameworks, accessibility, and more. If you’re in the Memphis area, check it out.

Here are the details.

I only know two of the other speakers (JD and John Lloyd). I’m looking forward to meeting the others, but even more so, getting to meet some of the other web-savvy designers in Memphis who are interested in these topics. Maybe I’ll see you there.

Spinboxes Optimized for Touchscreen

So what’s a spinbox? A picture is worth a thousand words:

Here’s the thousand word version (via):

A spin box — sometimes called a spinner control — is a collective term for the combination of a text box with an up-down control. Users can click arrow buttons (the up-down control) or press the UP ARROW or DOWN ARROW key to change the value in the text box. The value ascends or descends incrementally.

I’ve been optimizing web forms for use in iPhones and Androids. Not too long ago I ready a post by Luke Wroblewski on the topic (which used hotel search forms as an example – bonus for me). In Luke’s post, he calls attention to the fact that Kayak’s mobile app uses spinboxes for room and guest count instead of select drop-downs:

Screenshot of Kayak's iPhone app

Screenshot of Kayak's iPhone app

The up/down controls are sized and positioned optimally for input from a fingertip instead of a mouse.

I’ve seen these used in iPhone apps, but not in web forms. I wanted to make a form that used these but wasn’t sure how to mark on up. According to the forms chapter of “Dive into HTML5″, Opera will render a spinbox for input type="number", and Opera even respects the min and max attributes. That’s great, but Safari doesn’t respect the min and max attributes (yet), so using cool new HTML5 attributes for input isn’t going to work for me.

I decided to use jQuery to dynamically create a spinbox that uses a select dropdown as it’s source. The jQuery would grab the select and all its options, create a spinbox control that dyanimically updates the hidden select as the up/down buttons are pressed, while keeping the original select hidden.

Here’s an example I made that I wrote specifically for webkit (iPhones, Androids, or if you want to see it in the desktop, Safari or Chrome). Or here’s a screenshot:

A touch-screen optimized spinbox example

A touch-screen optimized spinbox example

Download a zip if you want to play around with it. I’m no JavaScript/jQuery expert, so I’d love to hear about any improvements. Note that my script and styles use the term ‘tapbox’, which was my way of saying ‘touchscreen optimized spinbox’.

More about spinboxes

For select drop downs with few options (like in my case, 4), a spinbox is a great substitute for a select box. Select boxes that have many options, like say 31 days in a ‘day of the month’ drop down, should likely stay in a select, and not be converted to a spinbox, else you risk triggering your old nintendo thumb by furiously tapping to get to the higher options.

Other situations in which a spinbox might be appropriate, as summed up in this article:

Spin boxes are useful when users don’t need to see the whole range of values in order to make a selection. For example, if the range is so familiar to users that they’ll be able to infer all values from seeing just one (such as Monday indicating days of the week), consider using a spin box.

Review of CSS Mastery, Second Edition

I don’t read many technical books about web site development with CSS. I probably learned like many of you likely did: online articles, right click/view source, firebug, and a hell of a lot of trial and error. I never take for granted that I’ve been able to provide bacon and diapers for my family by learning from these freely available resources. I’m taking a moment now for that to sink in…. it’s awesome.

You can’t do that and become a surgeon, right? Like you can’t walk up to someone who you know has recently had their appendix removed, right-click, view source, and replay the procedure, saving the information to implement later. If you could, I’d imagine there’d be lots of link bait blogs with headlines like “32+ Ass-Kicking Drugs That Help Prevent Heart Disease You Should be Prescribing to Your Patients, but (Probably) Aren’t.”

Anyway, let’s bring this back home. As easy as it is to find great content all over the internet that would educate you on every possible thing you could imagine regarding what you can do with CSS, there’s nothing like having a book to articulate concepts from beginning to end and provide a coherent narrative of the thought and methodology behind a technique’s implementation. Andy Budd’s CSS Mastery: Advanced Web Standards Solutions, Second Edition, accomplishes this.

CSS Mastery

CSS Mastery isn’t for those just starting out (although anyone would learn something from this book if they are familiar with CSS and HTML). This isn’t something that starts out with how to specify font sizes for the p element. Athough it touches on some fundamentals, you’ll want to have been using CSS for a while in order to get the most out of this book.

Chapter 1 is called “Setting the Foundations”, and addresses the use of meaningful markup, using classes vs ids, different versions of HTML and CSS, DOCTYPE, among other things. It gets your head around some of the parts you don’t learn just by zapping an element on someone else’s site with Firebug. There is a part about microformats that is mentioned here, and though it’s great information, it feels out of place among the other topics in this chapter.

Chapter 2, “Getting Your Styles to Hit the Target”, talks about selectors, specificity, inheritance, style sheet planning and organizing, and style guides. It’s good to know these before you start authoring your CSS style. I appreciated his explanation as to why he prefers one CSS file rather than splitting it up into smaller ones. I’ve noticed other authors advocate splitting them up, so it’s nice to see someone of Budd‘s stature offering some yang to balance the yin. (Note that it all depends on the site in question in anyway.)

Chapter 3, “Visual Formatting Model Overview”, describes the box model, differences with IE, positioning (relative/absolute/etc.) and floating. I particularly found helpful Budd’s description of how inline boxes work, and why they ignore certain properties like height and vertical padding and margins.

Chapter 4 is “Using Backgrounds for Effect”, and talks about using images for list bullets, various rounded corner techniques (including border-radius), multiple background images, opacity (including RGBa), drop shadows, image replacement techniques, and then some. I sensed that this chapter got beefed up a bit with the CSS 3 properties from the previous version of the book.

Chapter 5 is “Styling Links”, and mentions all sorts of interesting ways to play up links, including creating CSS-only tooltips.

Chapter 6 is “Styling Lists and Creating Nav Bars”, which is definitely one of the most common things I get asked about. Not only does this chapter discuss all the various proven methods of creating CSS-styled navigation, but also has a terrific section on how to create Flickr-style image maps.

In Chapter 7, “Styling Forms and Data Tables”, Budd shows how to style a calendar, and what markup he’d use to make various layout methods for a simple form. This is one chapter I think is a little weak. I would’ve loved to have seen this chapter fleshed out much more. The concepts from the calendar can be applied to any table, but it would be nice to see a real data table taken on here, something like what happened here. And though the form concepts mentioned here are common in the wild (like a blog comment form), they feel far from leaving someone with a mastery of tackling forms. It only seems to tackle basic form layout, but nothing further. We’ve seen in Chapter 5 some pizazz he’d throw on links, but what about form fields? What about warning of the inherent dangers of applying styles to form fields?

Chapter 8, “Layout”. This is a meaty chapter, which discusses how to create fixed, elastic, and liquid layouts, and the bonuses of each. Someone could have a field day playing with layouts and techniques used here.

If you’ve forgotten why web developers cuss IE so much, then Chapter 9, “Bugs and Bug Fixing”, will help you remember. The chapter mentions how to find and isolate bugs, and reminds you to “fix the problem, not the symptoms.” It then goes into various IE-releated bugs, why they happen, and how to prevent them. Budd also mentions the concept of graded browser support (‘graded’ as opposed to ‘supported’/'not supported’). Great read.

The final two chapters are the all-new case studies for sample sites “Roma Italia” (by Cameron Moll) and “Climb the Mountains” (by Simon Collison). Moll and Collison walk through their approach to building their sites, and walk you through the implementation of various techniques. These case studies serve as professional models for readers to learn from and experiment with. These aren’t just wireframes or isolated elements – they are fully fleshed out pages, professionally designed and developed by leaders in the field on web development. You’ll hear them describe CSS3 properties in their own words. Although there is some overlap among all three authors in subject matter, this is a pro in two respects: 1) the case studies can be independently of the rest of the book, and 2) what concept may not have congealed under one author would hopefully click with the reader by another.

I have some some minor issues with the book. This book seemed to be written over a span of time while the latest crop of browsers were just coming out. I didn’t see any mention of Internet Explorer 8, which was released in March of last year. Also, whenever a tech book has chunks of code, and we want to illustrate what’s different from one chunk of code to the next, color highlighting is very helpful. And although this book is in color, only Chapter 8 and Chapter 10 appear to use different font colors to illustrate changes in within blocks of code and markup. As I mentioned before, there is some slight overlap in content that the three authors were responsible for. And while this can be helpful, for someone reading the book straight through, it seems a little weird to have concepts re-explained as if the last chapter didn’t just do that. Though I point out these issues, the pros of the book outweigh the cons by a landslide.

I’m sure a question might be from someone who already owns the first edition, as to whether they benefit from purchasing the second. In my opinion, no. I should restate that I didn’t read the first edition, so take this all with a grain of salt, and I also don’t pick up CSS books on a regular basis. But I would imagine anyone who has read the first edition and has also regularly kept up with web sites like the authors’ blogs, 23ways.org, alistapart.com, css-tricks.com, etc., that person may not get much more from this text. However, if you feel out of practice with CSS sites and were wondering if you should brush off your old copy to read again, then get this one instead.

Recommended. $26. Available from Amazon.

Monetizing your code

I’ve toyed with offering affiliate links to Theme Forest from this site in the past. But since the people who typically visit my site tend to design and markup their own, it didn’t seem worth it (and the click-through numbers supported that). If anything, readers of this site would be on the selling end rather than the purchasing end.

Now I see that the same family of sites is offering Code Canyon, a marketplace for code, which also seems to fit the readers of my site (once again, the selling end rather than the purchasing). And if you aren’t the kind of person who sells their designs and themes, perhaps you are the type of person who would be interested in monetizing your javascript image gallery, or your php contact form, or whatever. It appears you can do that at CodeCanyon.net. (Disclaimer: Yes, I’m using my affiliate link, although it doesn’t really help me that much if you are a seller, so maybe you want to buy something, too? Go ahead, look around :) ).

I wonder if the quality of some of the things sold here are much better than what you can find in the jQuery plug-in repositories and free php tutorials. Are you any of you out there buying these things? Are any of you selling? If so, how’s it going?

A way we could potentially get around the fact that many web forms prevent plus signs in email addresses

Many of you are likely already familiar with the immensely useful feature of including plus signs (+) in Gmail addresses, such as the following:

askthecssguy+mileycyrusfanclub@gmail.com

This would allow me to sign up for account at another web site, and be able to track spam or apply filters based on everything after the plus sign.

The problem is that many web sites that ask for email addresses will reject addresses that contain a plus sign. To get around this, we could do one of two things:

  1. Contact every web site owner whose site doesn’t allow plus signs, and convince them to change their form validation.
  2. Get Gmail to recognize a special string of characters as the same as ‘+’.

I’d love to see Gmail implement a feature where a specially string of characters would serve the same purpose as ‘+’. That string would be made up of commonly accepted characters, like [a-z] and [0-9], but their special combination would trigger the Gmail application to treat it like a plus sign.

For example, let’s say Gmail enabled this for the following string of characters: zzzplussignzzz. So I would sign up for the Miley Cyrus fan club using the following address:

askthecssguyzzzplussignzzzmileycyrusfanclub@gmail.com

I chose ‘zzzplussignzzz’ because it is unlikely to be used in a legitimate email address, and it would be easy to protect any new Gmail signups from using that string, perhaps by using the ‘Sorry, that’s already taken’ indicator in case someone attempts to do so.