Category Archives: javascript

Make JavaScript updates (including AJAX) accessible

Towards the end of Laura Kalbag‘s excellent talk on accessibility at last night’s FrontEndLondon meetup, a question was asked about how to deal with when JavaScript updated the page.  There wasn’t really time to go through it, and really its something best shown with a demo.

There are a couple of aria attributes that are well-supported by screenreaders that can help you out with this.

Here’s a pared-down example of an implementation.

....
<ul aria-live="assertive" aria-relevant="all" id="list">
    <li>item one</li>
    <li>item two</li>
</ul>
<button type="button" id="addnew" aria-controls="list">Add new item</button>
<button type="button" id="remove" aria-controls="list">Remove last item</button>
....
//assuming jquery
//

window.onload = function () {
    mymodule();
}
//NB: this is not how you'd build a module in production, its pared down for clarity of what's important.
var mymodule = (function ($) {
  return function () {
    var addBtn = $("#addnew");
    var removeBtn = $("#remove")
    var list = $("#list");

    var addItem = function () {
      var xhr = $.ajax({url:"/"});
      list.attr("aria-busy", "true");//apply the busy state
      xhr.done(function (data) {
        var newLi = $('<li>New item</li>');
        list.append(newLi);
      });
      xhr.fail(function () {
        alert("something went wrong");
      });
      xhr.always(function () {
        list.attr("aria-busy", "false"); // don't just do this on success, do it always. your server may return an error.
      });
    };
    var removeItem = function (e) {
      var c = list.children();
      c.eq(c.length - 1).remove();
    };

    addBtn.on("click", addItem);
    removeBtn.on("click", removeItem);
  }
}(jQuery));

If you run this example, you will notice that the announcement just consists of the new text. For example, you’d hear “Remove last item.” then upon activating it you’d hear “item two”. There’s no further information such as whether the content has been added or removed. If your feature doesn’t make sense without that extra bit of information, then you’d want to do something slightly different, where you update the text of a separate element with aria-live set on it with the fuller message.

Note that ‘add’ makes an ajax call, but ‘remove’ just acts on the DOM. Both get announced.

There are 2 attributes you will definitely need:

  • aria-live
  • aria-busy

There are 3 attributes you will possibly need:

  • aria-atomic
  • aria-relevant
  • aria-controls

These aria attributes sit on block-level elements that contain the content that is going to change.

Aria-live

Indicates that this is a part of the page that will get updated even after the page has loaded.

When the element with this attribute has a content change, the assistive technology automatically picks up on it and deals with it without you having to do anything more.

Its values are: off (ignore changes, default), polite (announce new content when you’ve run out of content to read), assertive (announce new content at the first opportunity).

There used to be aria-live=”rude” but it was so badly abused and disrupted users so much that it got dropped.  Be considerate when using assertive.  Confirming a save action probably justifies assertive.  An updated news feed is better being polite.

Aria-busy

Indicates that an element’s content is in the process of changing.  Its values are true or false.

Unlike aria-live, this one is something that you’d dynamically update from JavaScript.

A good rule of thumb is that if you are showing a spinner over something to indicate activity, you probably also want to set aria-busy to true on the container element for the area is getting updated, and to false when it hides.

Aria-atomic

Should the whole area be announced when just one part of if has changed? Or just the bit that changed?

Its values are true (announce the whole region when something changes) or false (default).

TIP: if your area’s text is not being read out when it updates, sometimes adding aria-atomic=”true” fixes it.

Aria-relevant

What type of changes should be announced?

Values are one or more of additions (meaning elements being added), text, removals (again, of elements) and all, separated by a space.  Default is aria-relevant=”additions text”

Aria-controls

Indicates a relationship between an interactive element (like a link or button) and the element it changes.

Value is ID of the controlled element.

Software

Mac: System Preferences > Universal Access

From there you can check the box to Show Universal Access status in the menu bar for easier access.

You will get best results from working with Safari or Chrome rather than Firefox on Mac.

Windows: Visit Freedom Scientific and download the demo version of JAWS.  After 20 minutes of use, it stops and you have to reboot to get it going again, so plan your test time accordingly.

NVDA is another free, popular screenreader but has fewer functions than the longer-established, paid-for JAWS.

Hacking the <a> tag – implications for search engines

Bilawal Hameed recently posted up Hacking the <a> tag in 100 characters, where he uses JavaScript to capture a click event on a link and then redirects it to another page entirely.

Knowing that search engine crawlers have limited JavaScript support, I went to see if Google thinks his page links to paypal or not.

If you search in google for link:www.paypal.co.uk site:bilaw.al, you will see that his post shows up.

To check I wasn’t getting a false positive, I tried a slightly different URL.

If you search for link:www.paypal.com site:bilaw.al instead, you get no results.

Is it a problem? Can it be exploited for profit? Not as far as I’m aware, beyond damaging the quality of Google’s search engine data.

Accessible select box (dropdown) change events that work cross-browser, including IE, Chrome and touch devices

There’s a well-know issue with select elements where if you listen for the change event, it will trigger differently between browsers, and on IE it will trigger in a way that makes it inaccessible.

Take the following example: user tabs onto a select element and then uses the arrow key to move through the list. In IE (tested versions 7-9), this triggers the change event whereas other browsers will wait until you’ve moved off the element.

Try this demo on jsfiddle, it will alert the value of the option you’ve selected when ‘change’ event gets fired.

If you are using your select element for navigating to another page, the keyboard user will never be able to get past the first and second item in your list. If you are using the select element for loading in more content via AJAX (e.g. updating other field items based on a select box selection is quite common), then you are going to be hitting your server far more than necessary.

The solution is to bind to blur, click and keydown for IE and change for everything else (should include touch devices), and then a) filter out keypresses that aren’t spacebar or enter and b) check to see if the selected option has actually changed. The below code uses jQuery, but it is all possible via native JS or other libraries. Sadly it relies on checking the browser’s user agent as there isn’t a feature you can test for (if I’ve overlooked something I’d love to hear about it).

Have a look at the accessibile version on jsfiddle


var somemodule = (function () {
  var obj = {
    //some code
    bindDOM: function () {
      var evts = "";
      //accessibility workaround: onchange is good for non-ie; keydown, click and blur is good for ie (but not for chrome)
      //unfortunately we cannot detect this with feature support so must rely on browser support
      if ($jQ.browser.msie) {
        evts = "keydown click blur";
      }
      else {
        evts = "change";
      }
      this.elem.on(evts, $jQ.proxy(this.onFooChange, this));
    },
    onFooChange: function (e) {
      var id;
      if (e.type !== "keydown" || (e.which === 13 || e.which === 32)) {
        id = $jQ(e.target).val();
        if (id !== this.currentFoo) {
          this.currentFoo = id;
          this.getBar(id);
        }
      }
    },
  };
  
  //more code
  return obj;
}());

jQuery UI sortable incorrectly positioned on drag when page is scrolled

While this issue is a bit odd, there’s not much in the way of information online and I suspect it will become more common as people start adding support for smaller screens and mobiles to their sites.

Here was our problem:
When dragging a sortable element, positioning was fine unless you were scrolled down the page a little.

After some trial and error, we found it was created by a combination of body{offset-x: hidden;} and position:relative on one of the parent elements of the sortable widget.

Now we don’t want to go removing things from other people’s pages to fix our work, because it will almost certainly break something else (these are templates, so the risk is high and regression testing a big task). The solution was to put offset-x: auto on the same element that gets scrollable applied to it.

This is due to get fixed in jQuery UI 2 as they rewrite the sortable plugin.

Interface Developer’s quality checklist

Towards the end of a project or sprint, time to delivery can sometimes get crushed due to any number of reasons (late wireframe or design delivery, too many iterations, staff illness, contractors leaving, underestimation, overdelivering, changing business needs, etc.), and sadly it is usually testing time that cops it.

This checklist should help you check you’ve got your main bases covered.

Tools you’ll need

Checklist

  1. Having stable, valid code will save you a lot of debugging pain.  If you know your code is sound, then it is most likely a browser fault that is the cause of any further bugs from here onwards
    1. Run the W3C HTML validator on all pages and correct
    2. Run the W3C CSS validator on all pages and correct
    3. Run the WAI tool on all pages.
    4. Run your JavaScript code through JSLint
    5. If you are hoping to have good coverage on mobiles, run mobileOK on your pages
  2. Check the static text content for spelling and grammar.  Mistakes here will just make you look stupid and unprofessional.
  3. Check you’ve done a full run-through of the site in each supported browser.  You do have an agreed browser matrix don’t you?
  4. View your site without CSS, can you still read everything?
  5. Open up each template in a new tab and run through them using CTRL+Tab to check your layouts are all the same – do the edges of the main layout boxes sit at the same position on each page or do they jump a few pixels? Is the main heading at the same position (presuming your design intends that)?
  6. Run through all pages at 1024×768 resolution (or 800×600 if you are required to support it), do you have to scroll horizontally?
  7. Try using your site without JavaScript.   If you can’t then non-JS users will not be able to use your site and search bots will not be able to index all your content
  8. Have you remembered your print stylesheet? Print preview your pages and actually print the most likely to be printed (e.g. an article template).  Sometimes the preview lies.
  9. If you are using flash, check your non-flash fall-back works.  You do have a fall-back right?
  10. If you are using embedded media, check there is a fall-back for those without it and a link to the vendor site to download the plugin.
  11. If you have static links in the site, run a linkchecker.  I’ve used Xenu in the past which is fairly good, and free.
  12. Run your pages through YSlow to find any major issues
  13. If you are using XMLHttpRequest (often referred to as AJAX), test what happens when the server returns a failure (e.g. a 404 or 500 rather than 200 OK)
  14. Accessibility checklist (this isn’t a definitive list, if for example your navigation is inconsistent between pages then you’ve a problem that requires the team going back to the drawing board to solve)
    1. Your content is in a sensible order in the HTML.  If you are not sure, looking at the page with CSS off will help you decide.
      • e.g. you do not break up your main content paragraphs to line up your right hand promo boxes
    2. Go through a few pages with a screenreader and keyboard.
      • Can you get to all your links and form fields without the mouse?
      • Can you hear all your content?
      • Is hidden content still ‘perceivable’?  If you are hiding with display none or visibility hidden, screenreaders will ignore that content, but if you use position absolute with left being a large negative number, it will still get read out to the user.
    3. Test all your interactive features (e.g. accordions or sliders) with a keyboard, also is the screenreader able to read the information in them? (see my previous post about focus)
    4. Page sections are marked out with headings
    5. Headings do not skip levels.  This should be picked up in the HTML validation.
    6. Have a ‘skip to content’ link at the top of your page
    7. You can pause any animation or movement that is on by default
    8. All forms have a submit button
      • that especially includes select field (dropdown) navigation, it should never be executed from the onchange or onselect events
    9. Text can be resized in all browsers, IE6 does it differently so be sure to test if you support it
    10. All form fields have explicit labels (i.e. you use the for attribute to refer to the field’s ID rather than wrapping the field inside the label element)
    11. Missing alt attributes is a common mistake, but will be picked up in your HTML validation
    12. Foreground and background colours have sufficient contrast
    13. Testing for seizure-causing animation is difficult, but the safest course of action is not to flash anything more than 3 times in 1 second.
    14. Image maps have their links duplicated underneath as a list
    15. Any static links have sensible link text that indicates where the link will go on its own without the rest of the paragraph text around it.
    16. Any linked images have sensible alt text that indicates on its own where the link will go
    17. Specify what language the page is in.  The HTML validator will pick it up if it is missing.
    18. Tables of data have a summary and scope for each column and each row is defined

Get some focus: keyboard and mouse events

When we add interactivity, we use event handling.  A common trap is to handle the events that are fired by the mouse but forget about what non-mouse users need.

Click

Click events are obviously fired from the mouse clicking on an item, but they are also fired when the user is focussed on an element and presses enter, so click events are covered for keyboard users as long as they can tab onto them in the first place.

When you click on something, a focus event is fired as well as the click event, after all you are focussing on something when you click on it.  If you are listening for the focus event and attaching functionality to it firing, remember that this functionality will also occur when you click on the attached elements.

Mouseout/mouseover

Mouseout and mouseover events rely on a mouse to trigger them

For mouseout events, pair them with blur events

  • myelem.mouseout = function(){etc.}
    myelem.blur = myelem.mouseout;

For mouseover events, pair them with focus events but remember they will trigger on mouse click as well as mouseover

  • myelem.mouseover = function(){etc.}
    myelem.focus = myelem.mouseover;

See the code examples

(If you want to find out more about events, PPK has an excellent events write-up)

Get some focus

When you click on or tab to an element, a ‘focus’ event is fired.  Focus has a significant role if we want to make sure our websites and especially our interactive features are accessible to everyone.

Focus is by default indicated visually either using an outline around the active element or by the flashing cursor for typed input areas.  This indicator may vary between browsers.

Chrome Browser showing focus

Chrome Browser shows focus by having a orange line around the link

Firefox link showing focus

Firefox shows focus by having a dotted line around the link

IE link showing focus

IE shows focus by having a black dotted line around the link

However, there are only 2 types of element that can receive focus through the keyboard.

  • anchor elements with href attribute
    • <a href=”#”>…</a>
  • form field, for example
    • <input type=”text” /> and other input elements
    • <textarea></textarea>
    • <select>…</select>
    • <button>…</button>

Wherever you need to have user-triggered interactivity, you need to use one of these focusable elements for the trigger.  I’ll cover this in greater depth in a later post.

About tabindex

Yes, you can force elements to receive focus by giving them a tabindex.   However, you then mess up the order in which elements receive focus.  Instead of following the order in which the HTML was developed, the focus will run through the tabindexed elements by numerical order, then go onto the non-tabindexed elements.  This might result in the cursor jumping around the page, which is especially annoying if the page is long enough to scroll.

Try the code example to test it out