Placeholder Attribute Support in ALL browsers

Included along with jQuery, the following code allows you to include the HTML5 placeholder attribute work in older browsers. The idea is to find all the input elements that have a placeholder attribute that the browser is ignoring since it doesn’t understand. Check to see if the input value is empty. If it is empty, include the placeholder value temporarily as the value (preferably making it look like a placeholder). If the user focuses on the input, clear the placeholder value, which is the default behavior in browsers that support the placeholder value. When the user exits the input box, the script checks to see if there is a value. If not, reinstate the value of the placeholder.

The second script is for when the user submits the form: we want to make sure that the form is not alwasy submitting the placeholder value. The main issue with this function is that the user cannot actually enter data that matches the placeholder, so, if you’re going to use this function, make sure that the placeholder value is not one that a user would intentionally submit. For example, use ‘first name’ and ‘last name’ for names, rather than ‘john’ and ‘doe’. Use ‘phone number’ or ‘415.555.1212’ for phone numbers, and other implausible values, etc.

  //make HTML5 placeholders work in non supportive browsers
  $("input[placeholder]").each(function(){
    if($(this).val()==""){
     // $(this).addClass('hasplaceholder');
      $(this).val($(this).attr("placeholder"));
      $(this).focus(function(){
        if($(this).val()==$(this).attr("placeholder")) $(this).val("");
       // $(this).removeClass('hasplaceholder');
      });
      $(this).blur(function(){
        if($(this).val()==""){
	  // $(this).addClass('hasplaceholder');
           $(this).val($(this).attr("placeholder"));
        }
       });
    }
  });

$('form').submit(function(evt){
	$('input[placeholder]').each(function(){
		if($(this).attr("placeholder") == $(this).val()) {$(this).val('');}
	});
});

Here are the lines explained:

Finds and iterates thru each input with a placeholder attribute:
$("input[placeholder]").each(function(){

Checks to see if the value is empty
if($(this).val()==""){

Commented out, you can add this line to add a class to the inputs that currently don’t have a value, so you can stylize them to look like placeholders (in other words, change the color to light grey using CSS):
// $(this).addClass('hasplaceholder');

Find the value of the placeholder attribute and sets it as the value of the value attribute
$(this).val($(this).attr("placeholder"));

Create an onFocus event handler
$(this).focus(function(){

When focused, checks to see if the current value matches the value of the placeholder. If so, it clears the placholder
if($(this).val()==$(this).attr("placeholder")) $(this).val("");

If you included the class to stylize the placeholder look and feel, remove it when the user is focusing on this input
// $(this).removeClass('hasplaceholder');

Close out the onFocus event handler
});

Create an onBlur event handler for when the user exits the input box
$(this).blur(function(){

Check to see if the input box is empty (the user has NOT entered any data)
if($(this).val()==""){

If the value is empty, we’re going to not just put the placeholder in, we should also include a class to be able to stylize it as a placeholder would look:
// $(this).addClass('hasplaceholder');

Put the value of the placeholder in the value — as we did on page load above.
$(this).val($(this).attr("placeholder"));

Close out all the set up stuff
}
});
}
});

We also need to ensure that the element has a legitimate value when the form is sumbitted:

We create an onSubmit event handler:
$('form').submit(function(evt){

We go thru all the inputs that have the placeholder attribute:
$('input[placeholder]').each(function(){

If the current value matches the placeholder value, we clear it before sumbitting:
if($(this).attr("placeholder") == $(this).val()) {$(this).val('');}

We close out the function:
});
});

Note that if the element is ‘required’, the submit function would be different and we would test to see if the browser supports the placeholder attribute before doing any of this, but i am just providing a small snippet to show how easy (and possible) it is to make older browsers support HTML5 form features.

HTML5: Introduction to <canvas>

Canvas: Tutorial of basic canvas functionality, canvas properties and methods

The HTML5 Canvas specification is a JavaScript API for coding drawings. The canvas API allows the definition of a canvas context object as the <canvas> element on your HTML page inside which we can draw.

We can draw in both 2D and 3D (WebGL) context. 2D is available in all the modern Web browsers, IE9, and via excanvas.js in current versions of IE, and will be more thoroughly introduced below. 3D is still nascent, with only experimental implementations.

2D context provides a simple yet powerful API for performing quick drawing operation, on a 2D bitmap surface. There is no file format, and you can only draw using script. You do not have any DOM nodes for the shapes you draw — you’re drawing pixels, not vectors. OK, not true. You are drawing vectors, but once drawn, only the pixels are remembered.

Your first <canvas>

Being a very basic introduction to canvas, we are only going to cover basic shapes and lines. If you are unfamiliar with JavaScript, the syntax may at first seem a bit confusing. If you are familiar, it should make sense.

Step 1 is adding the <canvas> element to your document. In terms of HTML, the only step involved in adding a canvas to your document is adding the <canvas> element to your document:

<canvas id="flag" width="320" height="220">
You don't support Canvas. If you did, you would see a flag
</canvas>

That is it for the HTML part of it. . We could simply have written <canvas></canvas>. However, you should include an id for ease of JavaScript targeting, but you could also target via placement within the DOM. You can also define the width and height of the canvas, though you can define that in the CSS as well. We’ve also included alternative content for users that don’t support or otherwise can’t see your <canvas> content

With that, we’ve created your blank drawing board, or canvas. Everything else takes place in our JavaScript files. Step 2 is drawing on our canvas. From now on, everything is in javascript. We target the canvas node with getElementById(‘flag’) or getElementsByTagName(‘canvas’)[0], initialize a 2D context and start drawing using 2D context API commands. We can draw the Japanese flag:

<script>
var el= document.getElementById("flag");

if (el && el.getContext) {
var context = el.getContext('2d');
if(context){
context.fillStyle = "#ffffff";
context.strokeStyle = "#CCCCCC";
context.lineWidth = 1;
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
context.strokeRect(10, 10, 300, 200);
context.fillRect(10, 10, 300, 200);
context.shadowColor='rgba(0,0,0,0)';
context.fillStyle = "#d60818";
context.arc(160, 107, 60, 0, Math.PI*2, false);
context.fill();

}
}
</script>

The first line finds your <canvas> element by matching the element’s id attribute. Before creating the 2D context, we check to make sure that the canvas element has been found AND that the browser supports canvas by checking for the existence of the getContext method.

We have to then create a reference to a context using the getContext(contextId) method of the canvas element –‘2d’ and ‘3d’ are the contextId value choices. If context creation is successful, we are finally free to draw in our canvas.

Before drawing a shape, we must define the look and feel of the shape we want to draw by setting properties on the context object. We define the look of the border (stroke and linewidth) properties and the shadow of our first rectangle, which we draw with the strokeRect() method. We pass the same parameters as our SVG example: (10, 10, 300, 200). The four values are the x-offset, the y-offset, width and height respectively. Once the script executes a command, the script forgets about what it has done, and moves onto the next line of code. Unlike our SVG example, the rectangle we’ve drawn on our canvas is not part of the DOM.

When we draw our second rectangle using the fillRect method, which paints rectangles using the previously set fillStyle property, we need to pass the coordinates again as the DOM does not remember our first rectangle, though it can access pixel information.

Both rectangle method calls have the same parameters — 10, 10, 300, 200 — we’ve drawn our fill rectangle directly on top of our dropshadow rectangle. We could have created an object with those coordinates and passed it to both methods, but we can’t tell the canvas to access the first rectangle’s coordinates and copy to the second after the method call

As mentioned above, once you paint onto the canvas, the DOM has no recollection of what you’ve painted. Yes, the JavaScript remembers the values of the properties you’ve set, but the pixels that are places on the canvas are just pixels of color. As we start the process of drawing the disc or sun on our flag, the DOM has no recollection of which pixels were painted with which colors, but it does remember some properties we set, like our shadowColor. As we don’t want a shadow on the red circle, we can set the shadowColor to transparent.

Next we define our circle. We are not actually drawing the circle yet. context . arc(x-offset of center, y-offset of center, radius, startAngle, endAngle, anticlockwise) adds points to an arced path creating a virtual circumference of a circle described by the arguments, starting at the given start angle, in our case 0, which is on the right horizon, and ending at the given end angle, going in the given direction, which in our case is clockwise. Had our endAngle been less than 2Π, our circle would have been flattened: the start and end points connected by a straight line. Π would have created a half circle. We also re-define the fill color, from white to red. We then paint the circle we created using the fill() method that fills the described arc in the fillStyle color.

We haven’t even touched the surface of what <canvas> can do. http://ie.microsoft.com/testdrive/Graphics/CanvasPad/Default.html is a fun page to learn simple shapes, colors, shadows, text, images, transformation, animation and mouse movement with <canvas>.

Canvas functions and properties

Styles

Set the fillStyle

context.fillStyle="color"

Set the strokeStyle

   context.strokeStyle="color"

Line widths

   context.lineWidth=number

Line join styles

   context.lineJoin="bevel || round || miter"

Line end styles

   context.lineCap="butt || round || square"

Rectangles

Draw a rectangle

   context.strokeRect(left, top, width, height)

Fill a rectangle

   context.fillRect(left, top, width, height)

Erase a rectangle

   context.clearRect(left, top, width, height)

paths

Begin a path

   context.beginPath

Complete a path

   context.closePath

Move the pen to a location

   context.moveTo(horizontal, vertical)

Draw a straight line from current point to a new location

   context.lineTo(horizontal, vertical)

Stroke the current path

   context.Stroke()

Fill the current path

   context.fill()

Shadows

Shadow color

   context.shadowColor="color"

Shadow horizontal offset

   context.shadowOffsetX=number

Shadow vertical offset

   context.shadowOffsetY=number

Shadow blur

   context.shadowBlur=number

Canvas versus SVG

HTML5 Canvas and SVG may seem similar, in that they are both web technologies that allow you to create rich graphics inside the browser, but they are fundamentally different. In SVG, you ‘draw’ with XML. For canvas, you draw with JavaScript. Canvas is the painting of pixels onto a canvas, once painted, each pixel is forgotten. SVG, on the other hand, creates DOM nodes, accessible until deleted or until navigation away from the page. They both have their advantages and disadvantages.

SVG is resolution independent, making SVG an excellent choice for user interfaces of all sizes as it allows scaling for all screen resolutions. SVG is an XML file format enabling easy accessibility. SVG can be animated using a declarative syntax, or via JavaScript. Each element becomes part of and is accessible via the SVG DOM API in JavaScript. However, anything that accesses the DOM repeatedly slows the page down.

Canvas is all drawn in pixels. Zooming can lead to pixilation. Canvas is inherently less accsessible: accessibility is limited mainly to including fallback content should canvas not render. Interactivity requires redrawing of each pixel. There are no DOM nodes for anything you draw. There’s no animation API, instead timers are generally used for updating the canvas at quick intervals. Canvas gives you a surface to draw onto with the API of the context you choose. Canvas, however, is very well suited for editing of images, generating raster graphics such as for games or fractals, and operations requiring pixel-level manipulation. Canvas can also be exported to gif or jpeg.

Introduction to GeoLocation

Geolocation allows users to share their physical location with your application if they choose to. Especially useful in social networking, geo tagging, and mapping, but applicable to any type of application, geolocation enables developers to enhance the user experience, making content, social graphs and advertisements more relevant to the location of the user.

The browser will request the permission of the user before accessing geolocation information. Geolocation is an opt in feature: when your web application requests Geolocation information, mobile browsers create an alert, and the desktop browser asks via banner that pops up at the top of the browser window asking permission to access location information. The user can grant permission or deny it, and optionally remember the choice on that site. If permission is granted, the Geolocation information will be accessible to your scripts and any third party scripts included in the page, letting your application determine the location of the user, and maintain location as the user moves around.

Location information is approximate, not exact, being garnered from IP addresses, cell towers, Wi-Fi networks, GPS, or even getting the information through manual data entry by the user.  The geolocation API does not care how the client determines location as long as the data is received in a staddard way. Because determining location can take time, the geolocation API is asynchronous.

To determing browser support for geolocation use:

if(navigator.geolocation) {
   //geolocation is supported
}

The geolocation object provides for the getCurrentPosition() method that asynchronously returns the user’s current location.

if(navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(handle_success, handle_errors);
}

If successful, the callback function will return the current position with the coords property contains the more common latitude and longitude properties as well as the altitude, accuracy, altitudeAccuracy, heading and speed properties. The following script will return the alert the current latitude and longitude, and is available in the chapter files:

if(navigator.geolocation) {
 navigator.geolocation.getCurrentPosition(handle_success,handle_errors); 
 
function handle_success(position){ 
 alert('Latitude: ' + position.coords.latitude + '\n Longitude: ' + position.coords.latitude); 
 }
 
 function handle_errors(err) { 
 switch(err.code) 
    { 
   case err.PERMISSION_DENIED: alert("User refused to share geolocation data"); 
   break; 
 
   case err.POSITION_UNAVAILABLE: alert("Current position is unavailable"); 
   break; 
 
   case err.TIMEOUT: alert("Timed out"); 
   break; 
 
   default: alert("Unknown error"); 
   break; 
  }
 } 

 

}

The draft specification can be found at http://dev.w3.org/geo/api/spec-source.html#geolocation_interface. Geolocation is support in Firefox, Webkit and Opera, but not IE. It is anticipated that it will be supported in IE9.

HTML5: Introduction to <canvas>

Canvas: Tutorial of basic canvas functionality, canvas properties and methods

The HTML5 Canvas specification is a JavaScript API for coding drawings. The canvas API allows the definition of a canvas context object as the <canvas> element on your HTML page inside which we can draw.

We can draw in both 2D and 3D (WebGL) context. 2D is available in all the modern Web browsers, IE9, and via excanvas.js in current versions of IE, and will be more thoroughly introduced below. 3D is still nascent, with only experimental implementations.

2D context provides a simple yet powerful API for performing quick drawing operation, on a 2D bitmap surface. There is no file format, and you can only draw using script. You do not have any DOM nodes for the shapes you draw — you’re drawing pixels, not vectors. OK, not true. You are drawing vectors, but once drawn, only the pixels are remembered.

Your first <canvas>

Being a very basic introduction to canvas, we are only going to cover basic shapes and lines. If you are unfamiliar with JavaScript, the syntax may at first seem a bit confusing. If you are familiar, it should make sense.

Step 1 is adding the <canvas> element to your document. In terms of HTML, the only step involved in adding a canvas to your document is adding the <canvas> element to your document:

<canvas id="flag" width="320" height="220">
You don't support Canvas. If you did, you would see a flag
</canvas>

That is it for the HTML part of it. . We could simply have written <canvas></canvas>. However, you should include an id for ease of JavaScript targeting, but you could also target via placement within the DOM. You can also define the width and height of the canvas, though you can define that in the CSS as well. We’ve also included alternative content for users that don’t support or otherwise can’t see your <canvas> content

With that, we’ve created your blank drawing board, or canvas. Everything else takes place in our JavaScript files. Step 2 is drawing on our canvas. From now on, everything is in javascript. We target the canvas node with getElementById(‘flag’) or getElementsByTagName(‘canvas’)[0], initialize a 2D context and start drawing using 2D context API commands. We can draw the Japanese flag:

<script>
var el= document.getElementById("flag");

if (el && el.getContext) {
var context = el.getContext('2d');
if(context){
context.fillStyle = "#ffffff";
context.strokeStyle = "#CCCCCC";
context.lineWidth = 1;
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
context.strokeRect(10, 10, 300, 200);
context.fillRect(10, 10, 300, 200);
context.shadowColor='rgba(0,0,0,0)';
context.fillStyle = "#d60818";
context.arc(160, 107, 60, 0, Math.PI*2, false);
context.fill();

}
}
</script>

The first line finds your <canvas> element by matching the element’s id attribute. Before creating the 2D context, we check to make sure that the canvas element has been found AND that the browser supports canvas by checking for the existence of the getContext method.

We have to then create a reference to a context using the getContext(contextId) method of the canvas element –‘2d’ and ‘3d’ are the contextId value choices. If context creation is successful, we are finally free to draw in our canvas.

Before drawing a shape, we must define the look and feel of the shape we want to draw by setting properties on the context object. We define the look of the border (stroke and linewidth) properties and the shadow of our first rectangle, which we draw with the strokeRect() method. We pass the same parameters as our SVG example: (10, 10, 300, 200). The four values are the x-offset, the y-offset, width and height respectively. Once the script executes a command, the script forgets about what it has done, and moves onto the next line of code. Unlike our SVG example, the rectangle we’ve drawn on our canvas is not part of the DOM.

When we draw our second rectangle using the fillRect method, which paints rectangles using the previously set fillStyle property, we need to pass the coordinates again as the DOM does not remember our first rectangle, though it can access pixel information.

Both rectangle method calls have the same parameters — 10, 10, 300, 200 — we’ve drawn our fill rectangle directly on top of our dropshadow rectangle. We could have created an object with those coordinates and passed it to both methods, but we can’t tell the canvas to access the first rectangle’s coordinates and copy to the second after the method call

As mentioned above, once you paint onto the canvas, the DOM has no recollection of what you’ve painted. Yes, the JavaScript remembers the values of the properties you’ve set, but the pixels that are places on the canvas are just pixels of color. As we start the process of drawing the disc or sun on our flag, the DOM has no recollection of which pixels were painted with which colors, but it does remember some properties we set, like our shadowColor. As we don’t want a shadow on the red circle, we can set the shadowColor to transparent.

Next we define our circle. We are not actually drawing the circle yet. context . arc(x-offset of center, y-offset of center, radius, startAngle, endAngle, anticlockwise) adds points to an arced path creating a virtual circumference of a circle described by the arguments, starting at the given start angle, in our case 0, which is on the right horizon, and ending at the given end angle, going in the given direction, which in our case is clockwise. Had our endAngle been less than 2Π, our circle would have been flattened: the start and end points connected by a straight line. Π would have created a half circle. We also re-define the fill color, from white to red. We then paint the circle we created using the fill() method that fills the described arc in the fillStyle color.

We haven’t even touched the surface of what <canvas> can do. http://ie.microsoft.com/testdrive/Graphics/CanvasPad/Default.html is a fun page to learn simple shapes, colors, shadows, text, images, transformation, animation and mouse movement with <canvas>.

Canvas functions and properties

Styles

Set the fillStyle

context.fillStyle="color"

Set the strokeStyle

   context.strokeStyle="color"

Line widths

   context.lineWidth=number

Line join styles

   context.lineJoin="bevel || round || miter"

Line end styles

   context.lineCap="butt || round || square"

Rectangles

Draw a rectangle

   context.strokeRect(left, top, width, height)

Fill a rectangle

   context.fillRect(left, top, width, height)

Erase a rectangle

   context.clearRect(left, top, width, height)

paths

Begin a path

   context.beginPath

Complete a path

   context.closePath

Move the pen to a location

   context.moveTo(horizontal, vertical)

Draw a straight line from current point to a new location

   context.lineTo(horizontal, vertical)

Stroke the current path

   context.Stroke()

Fill the current path

   context.fill()

Shadows

Shadow color

   context.shadowColor="color"

Shadow horizontal offset

   context.shadowOffsetX=number

Shadow vertical offset

   context.shadowOffsetY=number

Shadow blur

   context.shadowBlur=number

Canvas versus SVG

HTML5 Canvas and SVG may seem similar, in that they are both web technologies that allow you to create rich graphics inside the browser, but they are fundamentally different. In SVG, you ‘draw’ with XML. For canvas, you draw with JavaScript. Canvas is the painting of pixels onto a canvas, once painted, each pixel is forgotten. SVG, on the other hand, creates DOM nodes, accessible until deleted or until navigation away from the page. They both have their advantages and disadvantages.

SVG is resolution independent, making SVG an excellent choice for user interfaces of all sizes as it allows scaling for all screen resolutions. SVG is an XML file format enabling easy accessibility. SVG can be animated using a declarative syntax, or via JavaScript. Each element becomes part of and is accessible via the SVG DOM API in JavaScript. However, anything that accesses the DOM repeatedly slows the page down.

Canvas is all drawn in pixels. Zooming can lead to pixilation. Canvas is inherently less accsessible: accessibility is limited mainly to including fallback content should canvas not render. Interactivity requires redrawing of each pixel. There are no DOM nodes for anything you draw. There’s no animation API, instead timers are generally used for updating the canvas at quick intervals. Canvas gives you a surface to draw onto with the API of the context you choose. Canvas, however, is very well suited for editing of images, generating raster graphics such as for games or fractals, and operations requiring pixel-level manipulation. Canvas can also be exported to gif or jpeg.

iPhone: HTML, CSS & JS Support


See Estelle at the 2nd annual CSS Summit
Wouldn’t it be cool to be able to use CSS3 and HTML5 unfettered by the lack of support in IE? Mobile developers for smart phones get to do just that! When developing for mobile devices using webkit browsers we can use CSS animations, transforms, multiple background images, rounded corners, text and box shadows, CSS columns, and HTML5 form elements.

In my CSS Summit session we’ll use some CSS3 features learned in earlier sessions to create a native looking iPhone web app. We’ll also cover some CSS UI and HTML5 form elements that will help you get up to speed on developing for mobile webkit. You don’t have to wait any longer to use CSS3! Join Us!



Safari and Safari for the iPhone support all HTML elements, including deprecated elements and even some proprietary elements that were never part of any W3C specifications. In addtion, Safari is supporting some HTML5 elements, even though the HTML5 specifications have not been finalized. I’ve also added the attributes that each element supports. I didn’t include id, class, style, dir & title, since all elements basically support those, but I did include element specific attributes as well as some webkit only attributes.

iPhone Support for CSS3 Selectors

All CSS Selectors are supported by Safari on the iPhone. See CSS browser support for a chartcomparison of all the selectors. Selectos include:

  • *
  • E
  • .class
  • #id
  • E F
  • E > F
  • E + F
  • E[attribute]
  • E[attribute=value]
  • E[attribute~=value]
  • E[attribute|=value]
  • :first-child
  • :link
  • :visited
  • :lang()
  • :before
  • ::before
  • :after
  • ::after
  • :first-letter
  • ::first-letter
  • :first-line
  • ::first-line
  • E[attribute^=value]
  • E[attribute$=value]
  • E[attribute*=value]
  • E ~ F
  • :root
  • :last-child
  • :only-child
  • :nth-child()
  • :nth-last-child()
  • :first-of-type
  • :last-of-type
  • :only-of-type
  • :nth-of-type()
  • :nth-last-of-type()
  • :empty
  • :not()
  • :target
  • :enabled
  • :disabled
  • :checked
  • see them all

iPhone Support for CSS3 properties

Almost all CSS2.1 properties and values are supported by Safari on the iPhone, except for some keyword values for content. Position: absolute is supported, but due to the viewport, does not appear to be supported. See the list of all CSS2.1 properties and values by browser for more details. In addition, the iPhone Safari browser supports some CSS3 type properties and values including:

Some CSS3 including the following, which will be discussed in future blog posts.

  • hsl(), rgba(), hsla() color support
  • native rounded corners (-webkit-border-radius)
  • IE box model (-webkit-box-sizing)
  • Shadows on text (text-shadow was in CSS2.0)
  • Shadows on elements (-webkit-box-shadow)
  • multiple background images
  • opacity /gradient transparency
  • @font-face web fonts
  • CSS Animation
  • Media Queries
  • namespaces

iPhone & Safari Support for HTML elements, including HTML5

includes HTML attributes for the iPhone and Safari

Below is a grid of all of the elements, including deprecated elements (at the way bottom), and HTML5 elements interspersed with HTML4 elements in alphabetical order.

<ELEMENT> Element Name Safari
Version
iPhone Support Attributes (and Notes in italic)
Elements occuring outside the body element
<!DOCTYPE> Document Type Declaration 1.0 1.0
<html> html 1.0 1.0 manifest (Saf. 4, iphone 2.2)
<head> document head 1.0 1.0 profile
<base /> url base for links 1.0 1.0 href, target
<link /> link 1.0 1.0 charset, href, media, rel, rev, target
<meta /> meta 1.0 1.0 content, name, http-equiv, scheme
<style> style 1.0 1.0 media, type
<script> script 1.0 1.0 charset, defer, language, src, type
<title> document title 1.0 1.0
Elements Occuring in the <body> in HTML 4.01 and HTML5
<body> document body 1.0 1.0 bgproperties (value: fixed)
<a> Anchor 1.0 1.0 different event handlers for iPhone than Safari
accesskey, charset, href (required), hreflang, rel, rev, shape (rect/cirlce/poly), target (deprecated, but useful), type
<abbr> Abbreviation 1.0 1.0 title shows on hover in Safari
<acronym> acronym 1.0 1.0 title shows on hover in Safari
<address> address 1.0 1.0 italic
<area> image map area 1.0 1.0 accesskey, alt (required), coords, href (required), hreflang, shape (rect/cirlce/poly), target
<article> HTML5
<aside> HTML5
<audio> audio 3.1 3.0 HTML5: Similar to object, can nest sources and content to cascade until supported found.
Audio support includes AAC, M4A, MP3, Wave, AIFF , Apple Lossless, Quicktime, but not OGG;

autoplay, controls, end, loopend, loopstart, playcount, src, start
<bdo> bi-directional override 1.0 1.0
<blockquote> long quote 1.0 1.0 cite
<br> break return or forced line break 1.0 1.0
<button> push button 1.0 1.0 accesskey, disabled, type, value
<canvas> canvas drawing region 1.3 1.0 HTML5: Stroke and fill colors, rgba/hsla colors, paths, rectangles, shadows, gradients, patterns, translations, rotation and scale
<caption> caption 1.0 1.0
<cite> citation 1.0 1.0
<code> code 1.0 1.0
<col /> column 1.0 1.0 char, charoff, span
<colgroup> column group 1.0 1.0 char, charoff, span
<dd> definition description 1.0 1.0
<del> delete 1.0 1.0 datetime
<dfn> definition 1.0 1.0
<div> generic block element 1.0 1.0 aria-checked, aria-level, aria-pressed, aria-valuemax, aria-valuemin, aria-valuenow, role (Safari 4.0)
<dl> definition list 1.0 1.0
<dt> definition term 1.0 1.0
<em> emphasized text 1.0 1.0
<fieldset> field set 1.0 1.0
<figure> HTML5
<footer> HTML5
<form> form 1.0 1.0 accept, accept-charset, action, enctype. method, target
<frame /> frame 1.0 1.0 frameborder, longdesc, marginheight, marginwidth, noresize, scrolling (yes/no/auto), src
<frameset> frameset 1.0 1.0 cols, rows
<h1-6> headers 1.0 1.0
<header> HTML5
<hgroup> HTML5
<hr /> horizontal rule 1.0 1.0
<iframe> internal frame 1.0 1.0 frameborder, longdesc, marginheight, marginwidth, scrolling (yes/no/auto), src
<img /> image 1.0 1.0 alt (required), composite, ismap, longdesc, src, usemap
<input /> input 1.0 1.0 accept, accesskey, alt, autocapitalize (iphone 1.1, values: on/off), autocomplete, autocorrect (iphone 1.1, values: on/off), autosave (safari), checked, disabled, incremental (safari), ismap, max, maxlength, min, placeholder, results, src, type, usemap, value
<ins> Insert 1.0 1.0 datetime
<kbd> keyboard 1.0 1.0
<keygen> key generation 1.0 1.0 challenge, keytype
<label> label 1.0 1.0 accesskey, for
<legend> caption for fieldset 1.0 1.0 accesskey
<li> list item 1.0 1.0 type, value
<map> image map 1.0 1.0
<mark> HTML5
<meter> HTML5
<object> object 1.0 1.0 archive, classid, codetype, data, declare, loop, type, usemap
<ol> ordered list 1.0 1.0 type
<optgroup> option group 1.0 1.0 disabled, label
<option> option 1.0 1.0 disabled, label, selected, value
<p> paragraph 1.0 1.0
<param> parameter 1.0 1.0 type, value, valuetype
<pre> preformatted text 1.0 1.0
<progress> HTML5
<q> inline quotation 1.0 1.0 cite
<samp> sample computer code 1.0 1.0
<select> option selector 1.0 1.0 disabled, multiple
<source> 3.1 HTML5
media
<span> span (generic non-semantic container) 1.0 1.0 aria-checked, aria-level, aria-pressed, aria-valuemax, aria-valuemin, aria-valuenow, role (Safari 4)
<strong> strong emphasized text 1.0 1.0
<sub> subscript 1.0 1.0
<sup> superscript 1.0 1.0
<table> data table 1.0 1.0 frame (values: above, below, hsides, vsides, rhs, lhs, box, border), rules (values: none, groups, rows, cols, and all), summary
<tbody> table body 1.0 1.0 char, charoff
<td> table data cell 1.0 1.0 abbr, axis, char, charoff, colspan, headers, rowspan, scope
<textarea> text area 1.0 1.0 accesskey, cols, disabled, readonly, rows, wrap
<time> HTML5
<tfoot> table footer 1.0 1.0 char, charoff
<th> table header cell 1.0 1.0 abbr, axis, char, charoff, colspan, headers, rowspan, scope
<thead> table head 1.0 1.0 char, charoff
<tr> table row 1.0 1.0 char, charoff
<ul> unordered list 1.0 1.0
<var> variable 1.0 1.0
<video> video 3.1 3.0 HTML5
autoplay, controls, end, loopend, loopstart, playcount, poster, src, start
Elements you should not be using, that are still valid
<tt> teletype 1.0 1.0
<i> italic
<b> bold
<big> big font
<small> small font
<noframes> no frames 1.0 1.0
<noscript> no script 1.0 1.0
Elements that are deprecated or were never in a W3C spec, but you may still see on older websites
<applet> applet 1.0
<center> center 1.0 1.0
<dir> direction 1.0 1.0
<embed> embed 1.0 1.0 use object instead
hidden, loop, pluginpage, pluginspage, pluginurl
<font> font 1.0 1.0
<layer> layer 1.0 1.0
<listing> listing 3.0 1.0 use <pre> instead. from HTML 3.2
<marquee> ,arquee 1.0 1.0 behavior, direction, loop, scrollamount, scrolldelay, truespeed
<menu> menu 1.0 1.0
<nobr> no break 1.0 1.0
<noembed> no embed 1.0 1.0
<nolayer> no layer 1.0 1.0
<plaintext> plaintext 1.0 1.0
<strike> strikethrough 1.0 1.0 use <del>
<u> underline
<wbr> with breaks 1.0 1.0
<xmp> sequence of literal characters 1.o 1.0


Safari and iPhone Event Handlers:

Event Safari iPhone Explanation
onabort 1.0 1.0 When an image element is aborted during load. (for <img /> elements)
onbeforecopy 1.3 before the element is copied.
onbeforecut 1.3 before the element is cut.
onbeforepaste 1.3 before the element has something pasted into it.
onbeforeunload 1.3 before the element is unloaded from the page.
onblur 1.0 1.0 when the element loses focus.
onchange 1.0 1.0 when the element changes its value.
onclick 1.0 1.0 when the element is clicked.
oncontextmenu 1.1 when the element is right-clicked or when the mouse button is held down long enough to generate a contextual menu.
oncopy 1.3 when the element is copied.
oncut 1.3 when the element is cut.
ondblclick 1.0 when the element is double-clicked.
ondrag 1.3 when the element is dragged.
ondragend 1.3 when the element is done being dragged.
ondragenter 1.3 when a drag has entered the element.
ondragleave 1.3 when a drag has left the element.
ondragover 1.3 when a drag is over the element.
ondragstart 1.3 when the element has started to be dragged.
ondrop 1.3 when the element is dropped.
onerror 1.0 1.0 when the element has an error in loading.
onfocus 1.0 1.0 when the element gets focus.
ongesturechange 2.0 When fingers are moved during a gesture.

(proprietary)

ongestureend 2.0 When the gesture ends (when there are 1 or 0 fingers touching the surface).

(proprietary)

ongesturestart 2.0 When two or more fingers touch the surface.

(proprietary)

oninput 1.3 1.0 when text is entered into the element.
onkeydown 1.0 1.0 when a key is pressed over the element.
onkeypress 1.0 1.0 when a key is pressed and released over the element.
onkeyup 1.0 1.0 when a key is released over the element.
onload 1.0 1.0 when the element finishes loading.
onmousedown 1.0 1.0 when the mouse button is pressed over the element.
onmousemove 1.0 1.0 when a key is moved within the element.
onmouseout 1.0 1.0 when the mouse leaves the element.
onmouseover 1.0 1.0 when the mouse is over the element.
onmouseup 1.0 1.0 when the mouse button is released over the element.
onmousewheel 1.0 1.0 when the mouse wheel button is rotated.
onorientationchange 1.1 When the orientation of the device changes.
onpaste 1.3 when the element is pasted.
onreset 1.0 1.0 when the form element is reset.
onresize 1.0 1.0 when the element is resized.
onscroll 1.2 1.0 when the element is scrolled (a text box would use this, for example).
onsearch 1.3 when a search is performed.

(proprietary)

onselect 1.0 1.0 when text within the element is selected.
onselectstart 1.3 when the element begins to be selected. You can use this to prevent selections.
onsubmit 1.0 1.0 when the form element is submitted.
ontouchcancel 2.0 When the system cancels tracking for the touch.

(proprietary)

ontouchend 2.0 When a given event lifts from the surface.

(proprietary)

ontouchmove 2.0 When a finger for a given event moves on the surface.

(proprietary)

ontouchstart 2.0 When a finger for a given event touches the surface.

(proprietary)

onunload 2.1 when the element is unloaded from the page.

Other iPhone posts in my blog

16 Common JavaScript Gotchas

We all know that JavaScript can trip you up. Here are a 16 common traps that can trip you up when coding javascript. You likely know most of the code on the page, but if you keep these 16 gotchas in your mind, coding and debugging will be less of a headache:

  1. Case sensitivity: Variable names, properties and methods are all case sensitive
  2. Mismatching quotes, parenthesis or curly braces will throw an error
  3. Conditional Statments:3 common gotchas
  4. Line breaks: Always end statements in semi-colons to avoid common line break issues
  5. Punctuation:Trailing commas in object declarations will trip you up
  6. HTML id conflicts
  7. Variable Scope: global versus local scope
  8. string replace function isn’t global
  9. parseInt should include two arguments
  10. ‘this’ and binding issues
  11. Function overloading: Overwriting functions, as overloading doesn’t exist
  12. Setting default values for parameters in case you omit them
  13. For each loops are for objects, not arrays
  14. switch statements are a little tricky
  15. Always check for Undefined before checking for null
  16. Function location may matter
Case Sensitivity
Variables and function names are case sensitive. Like mismatched quotes, you already know this. But, since the error may be silent, here is the reminder. Pick a naming convention for yourself, and stick with it. And, remember that native javascript function and CSS properties in javascript are camelCase.

getElementById('myId') != getElementByID('myId'); // it should be "Id" not "ID"
getElementById('myId') != getElementById('myID'); // "Id" again does not equal"ID"
document.getElementById('myId').style.Color; // returns "undefined"
Mismatching quotes, parenthesis and curly brace
The best way to avoid falling into the trap of mismatched quotes, parentheses and curly brackets is to always code your opening and closing element at the same time, then step into the element to add your code. Start with:

var myString = ""; //code the quotes before entering your string value
function myFunction(){
     if(){   //close out every bracket when you open one.

	 }
}

//count all the left parens and right parens and make sure they're equal
alert(parseInt(var1)*(parseInt(var2)+parseInt(var3))); //close every parenthesis when a parenthesis is open

Every time you open an element, close it. Put the arguments for a function into the parenthesis after you’ve added the closing parenthesis. If you have a bunch of parenthesis, count the opening parenthesis and then the closing parenthesis, and make sure those two numbers are equal.

Conditional statements (3 gotchas)
  1. All conditional comments must be within parentheses (duh!)
    if(var1 == var2){}
  2. Don’t get tripped up by accidentally using the assignment operator: assigning your second argument’s value to your first argument. Since it’s a logic issue, it will always return true and won’t throw an error.
    if(var1 = var2){} // returns true. Assigns var2 to var1
  3. Javascript is loosely typed, except in switch statements. JavaScript is NOT loosely typed when it comes to case comparisons.
    var myVar = 5;
    if(myVar == '5'){ // returns true since Javascript is loosely typed
      alert("hi");  //this alert will show since JS doesn't usually care about data type.
    }
    switch(myVar){
      case '5':
      alert("hi"); // this alert will not show since the data types don't match
    }
Line Breaks
  • Beware of hard line breaks in JavaScript. Line breaks are interpreted as line-ending semicolons. Even in a string,if you include a hard line break in between quotes you’ll get a parse error (unterminated string).
        var bad  = '<ul id="myId">
                       <li>some text</li>
                       <li>more text</li>
                    </ul>'; // unterminated string error
    
        var good = '<ul id="myId">' +
                       '<li>some text</li>' +
                       '<li>more text</li>' +
                   '</ul>'; //correct
  • The line break being interpreted as a semi-colon rule, discussed above, does not hold true in the case of control structures: line breaks after the closing parenthesis of a conditional statement is NOT given a semi-colon.

Always use semi-colons and parenthesis so you don’t get tripped up by breaking lines, so your code is easier to read, and, less thought of but a source of quirks for those who don’t use semicolons: so when you move code around and end up with two statements on one line, you don’t have to worry that your first statement is correctly closed.

Extra commas
The last property in any JavaScript object definition must never end with a comma. Firefox won’t barf on the trailing, unnecessary commas, but IE will.

HTML id conflicts
The JavaScript DOM bindings allow indexing by HTML id. Functions and properties share the same namespace in JavaScript. So, when an id in your HTML has the same name as one of your functions or properties, you can get logic errors that are hard to track down. While this is more of a CSS best practice issue, it’s important to remember when you can’t solve your javascript issue.

var listitems = document.getElementsByTagName('li');

var liCount = listitems.length; // if you have <li id="length">, returns that <li> instead of a count.

If you’re marking up (X)HTML, never use a javascript method or property name as the value for an ID. And, when you’re coding the javascript, avoid giving variables names that are ID values in the (X)HTML.

variable scope
Many problems in javascript come from variable scope: either thinking that a local variable is global, or overwriting a global variable unwittingly with what should be a local variable in a function. To avoid issues, it’s best to basically not have any global variables. But, if you have a bunch, you should know the “gotchas”.

Variables that are not declared with the var keyword are global. Remember to declare variables with the var keyterm to keep variables from having global scope. In this example, a variable that is declared within a function has global scope because the var ke

anonymousFuntion1 = function(){
	globalvar = 'global scope'; // globally declared because "var" is missing.
	return localvar;
}();

alert(globalvar); // alerts 'global scope' because variable within the function is declared globally

anonymousFuntion2 = function(){
	var localvar = 'local scope'; //locally declared with "var"
	return localvar;
}();

alert(localvar); // error "localvar is not defined". there is no globally defined localvar

Variable names that are introduced as parameter names are local to the function. There is no conflict if your parameter name is also the name of a global variable as the parameter variable has local scope. If you want to change the global variable from within a function that has a parameter duplicating the global variable’s name, remember that global variables are properties of the window object.

var myscope = "global";

function showScope(myscope){
  return myscope; // local scope even though there is a global var with same name
}
alert(showScope('local'));

function globalScope(myscope){
  myscope = window.myscope; // global scope
  return myscope;
}
alert(globalScope('local'));

You should even declare variables within loops

for(var i = 0; i < myarray.length; i++){}
string replace
A common mistake is assuming the behavior of the string replace method will impact all possible matches. Infact, the javascript string replace method only changes the first occurrence. To replace all occurrences, you need to set the global modifier.

  var myString = "this is my string";
  myString = myString.replace(/ /,"%20"); // "this%20is my string"
  myString = myString.replace(/ /g,"%20"); // "this%20is%20my%20string"
parseInt
The most common error with parding integers in javascript is the assumption that parseInt returns the integer to base 10. Don’t forget the second argument, the radix or base, which can be anything from 2 to 36. To ensure you don’t screw up, always include the second parameter.

parseInt('09/10/08'); //0parseInt('09/10/08',10); //9, which is most likely what you want from a date.
‘this’
Another common mistake is forgetting to use ‘this‘. Functions defined on a JavaScript object accessing properties on that JavaScript object and failing to use the ‘this’ reference identifier. For example, the following is incorrect:

function myFunction() {
  var myObject = {
     objProperty: "some text",
     objMethod: function() {
		alert(objProperty);
		}
     };
  myObject.objMethod();
} 

function myFunction() {
  var myObject = {
     objProperty: "some text",
     objMethod: function() {
		alert(this.objProperty);
		}
     };
  myObject.objMethod();
}

There’s an A List Apart article that puts this binding issue into plain English

Overwriting functions / overloading functions
When you declare a function more than once, the last declaration of that function will overwrite all previous version of that function throwing no errors or warnings. This is different from other programming languages, like java, where you can have multiple functions with the same name as long as they take different arguments: called function overloading. There is no overloading in javascript. This makes it vitally important to not use the names of core javascript functions in your code. Also, beware of including multiple javascript files, as an included script may overwrite a function in another script. Use anonymous functions and namespaces.

(function(){
	// creation of my namespace
    // if namespace doesn't exist, create it.	if(!window.MYNAMESPACE) {		window['MYNAMESPACE'] = {}; 		}

    // this function only accessible within the anonymous function
    function myFunction(var1, var2){
		//local function code goes here
    }

    /* attaches the local function to the namespace
       making it accessible outside of the anoymous function with use of namespace */
    window['MYNAMESPACE']['myFunction'] = myFunction; 

 })();// the parenthesis = immediate execution	  // parenthesis encompassing all the code make the function anonymous
Missing Parameters
A common error is forgetting to update all the function calls when you add a parameter to a function. If you need to add a parameter to handle a special case call in your function that you’ve already been calling, set a default value for that parameter in your function, just in case you missed updating one of the calls in one of your scripts.

function addressFunction(address, city, state, country){
      country = country || "US"; // if country is not passed, assume USA
      //rest of code
    }

You can also get the length of the argument array. But we’re focusing on “gotchas” in this post.

For each
The “for” loop in javascript will iterate it over all object attributes, both methods and properties, looping thru all of the property names in an object. The enumeration will include all of the properties—including functions and prototype properties that you might not be interested in—so filter out the values you don’t want using hasOwnProperty method and typeof to exclude functions. Never use for each to iterate thru an array: only use for each when needing to iterated thru object properties and methods.

  • for each (var myVar in myObject) iterates a specified variable over all values of object’s properties.
  • for (var myVar in myObject) iterates a specified variable over all the properties of an object, in arbitrary order. The for...in loop does not iterate over built-in properties. For each distinct property the code is executed
  • for (var 1=0; i < myArray.length; i++) iterates thru all the elements of an array.

To fix the problem, generally you’ll want to opt for for ... in for objects and use the for loop for arrays:

listItems = document.getElementsByTagName('li');

for each (var listitem in listItems){
    // this goes thru all the properties and methods of the object,
    // including native methods and properties, but doesn't go thru the array: throws error!
   }

//since you have an array of objects that you are looping thru, use the for loop
for ( var i = 0; i < listItems.length; i++) {
    // this is what you really wanted
   }
Switch statements
I wrote a whole blog post on switch statement quirks, but the gist is:

  • there is no data type conversion
  • once there is a match, all expressions will be executed until the next break or return statement is executed, and
  • you can include multiple cases for a single block of code
Undefined ≠ null
Null is for an object, undefined is for a property, method or variable. To be null, your object has to be defined. If your object is not defined, and you test to see whether it’s null, since it’s not defined, it can’t test, and will throw an error.

if(myObject !== null  && typeof(myObject) !== 'undefined') {
	//if myObject is undefined, it can't test for null, and will throw an error
}

if(typeof(myObject) !== 'undefined' && myObject !== null) {
	//code handling myObject
}

Harish Mallipeddi has an explanation of undefined versus null

Function location can matter
There are two ways to declare function: When declaring a function in the form of a variable assignment, location does matter:

var myFunction = function(arg1, arg2){
  // do something here
};

A function declared with

function myFunction (arg1, arg2){}

can by used by any code in the file no matter its location (before or after the function declaration). A function declared with the variable assignment syntax can only be used by code that executes after the assignment statement that declares the function.

WAI-ARIA: Accessible Rich Internet Applications basics

What is ARIA?

ARIA stands for Accessible Rich Internet Applications. With the proliferation of internet applications, there has been an increase in the number of sites requiring javascript that update without page refreshes. This imposes accessiblity issues that weren’t addressed by WCAG 1, as those specifications were written when “sites must work without javascript” was a reasonable accessibility specification. With the increase of web based “applications” (versus “sites”) requiring JavaScript, and improved support of javascript in assistive technologies, new accessibility issues have emerged. ARIA attempts to handle some of those issues. Through the inclusion of roles, states and properties your dynamically generated content can be made accessible to assistive technologies. Additionally, static content can be made more accessible thru these additional, enhanced semantic cues.

Why use ARIA?

By including ARIA accessibility features on your website you are enhancing the accessibility of your site or application. By including roles, states and properties, ARIA enables the developer to make the code semantically richer for the assistive technology user. ARIA enables semantic description of element or widget behavior and enables information about groups and the elements within them. ARIA states and properties are accessible via the DOM.

Similar to including the title attribute, ARIA is purely an enhancement and will not harm your site in any way. In other words, there is no valid reason to not include these features! DojoTools currently supports ARIA. Now that IE8 and Firefox 3 (both in beta at the time of this writing) support ARIA, the other JavaScript libraries should soon follow suit.

The easiest to include and most important properties of ARIA are the inclusions for the role attribute, and inclusion of states and properties.

How to incorporate ARIA

  1. Use XHTML the way it was meant to be used wherever possible. Limit ARIA usage to augment XHTML: only use it when XHTML does not support all the semantics required .
  2. Apply ARIA the role attribute in cases where the XHTML needs to be semantically enhanced and in cases where elements are being employed outside of their semantic intent. This includes setting up relationships between related elements (grouping)
  3. Set ARIA states and properties. Set the properties and initial state on dynamically and user changing elements. States, such as “checked”, are properties that may change often. Assistive technology that supports ARIA will react to state and property changes. role changes, on the other hand, may confuse the assistive technology
  4. Support full, usable keyboard navigation. Elements should all be able to have keyboard focus. I am not covering this here, but you can read up on this at For a more in-depth understanding of keyboard navigation see ARIA Best Practices
  5. Make the visual user interface visually match the defined states and properties in browsers that support the ARIA CSS pseudo-classes.

The ARIA role attribute

The role attribute enables the developer to create semantic structure on repurposed elements. While to a sited user, the above example of a span repurposed as a checkbox is not noticeable, the role attribute makes this seemingly non-semantic mark up accessible, usable and interoperable with assistive technologies. Two notes about roles: 1) once set, a role should not be dynamically changed, since this will confuse the assistive technology, and 2) roles take precendence over element default semantic meaning.

Example: Your designer insists that they want the checkboxes on your page to look a certain way. “Impossible” you say. You know that you can use CSS to make a span look like a checkbox. The sited user would never know that your weren’t using <input type="checkbox"...., but for accessibility concerns, you know a screen reader user will not know it’s a checkbox. With the ARIA role attribute included in your code, a both a browser and screen reader that support ARIA, you can make your repurposed span accessible with:

<span role="checkbox" aria-checked="true" tabindex="0" />

Of course, this case makes me cringe, since it doesn’t work without javascript and it is not inherintly semantic. However, if you are creating a web application requiring javascript, and you are coding this when browsers actually support ARIA, then you gotta do what you gotta do. If you include spans transformed into checkboxes, you will need to include equivalent unobtrusive onkeydown and onclick events.

Implementation of the ARIA role attribute

<ul role="navigation">
  <li><a href="mypage.html">My Page</li>
  <li>....
</ul>

Values for the ARIA role attribute (For descriptions, roll over the items below)

alert
A message with an alert or error information
alertdialog

A separate window with an alert or error information
application
A software unit executing a set of tasks for its users
banner
A banner is usually defined as the advertisement at the top of a web page. The banner content typically contains the site or company logo and other key advertisements for the site
button
Allows for user-triggered actions
checkbox
A control that has three possible values, (true, false, mixed)
columnheader
A table cell containing header information for a column
combobox
Combobox is a presentation of a select, where users can type to locate a selected item
contentinfo
This is information about the content on the page. For example, footnotes, copyrights, links to privacy statements, etc. would belong here
definition
The contents of the associated element represent a definition (e.g., of a term or concept). If there is a dfn element within the contents, then that represents the term being defined.
description
Descriptive content for a page element which references this element via describedby.
dialog
A dialog is a small application window that sits above the application and is designed to interrupt the current processing of an application in order to prompt the user to enter information or require a response
directory
A list of references to members of a single group.
document
Content that contains related information, such as a book.
grid
A grid contains cells of tabular data arranged in rows and columns (e.g., a table).
gridcell
A gridcell is a table cell in a grid. Gridcells may be active, editable, and selectable. Cells may have relationships such as controls to address the application of functional relationships.
group
A group is a section of user interface objects which would not be included in a page summary or table of contents by an assistive technology. See region for sections of user interface objects that should be included in a page summary or table of contents.
heading
A heading for a section of the page.
img
An img is a container for a collection elements that form an image.
link
Interactive reference to a resource (note, that in XHTML 2.0 any element can have an href attribute and thus be a link)
list
Group of non-interactive list items. Lists contain children whose role is listitem.
listbox
A list box is a widget that allows the user to select one or more items from a list. Items within the list are static and may contain images. List boxes contain children whose role is option.
listitem
A single item in a list. Should be within an element with the role of list
log
A region where new information is added and old information may disappear such as chat logs, messaging, game log or an error log. In contrast to other regions, in this role there is a relationship between the arrival of new items in the log and the reading order. The log contains a meaningful sequence and new information is added only to the end of the log, not at arbitrary points.
main
This defines the main content of a document.
marquee
A marquee is used to scroll text across the page.
menu
Offers a list of choices to the user.
menubar
A menubar is a container of menu items. Each menu item may activate a new sub-menu. Navigation behavior should be similar to the typical menu bar graphical user interface.
menuitem
A link in a menu. This is an option in a group of choices contained in a menu.
menuitemcheckbox
Defines a menuitem which is checkable (tri-state).
menuitemradio
Indicates a menu item which is part of a group of menuitemradio roles.
navigation
This is a collection of links suitable for use when navigating the document or related documents.
note
The content is parenthetic or ancillary to the main content of the resource.
option
A selectable item in a list represented by a select.
presentation
An element whose role is presentational does not need to be mapped to the accessibility API.
progressbar
Used by applications for tasks that take a long time to execute, to show the execution progress.
radio
A radio is an option in single-select list. Only one radio control in a radiogroup can be selected at the same time.
radiogroup
A group of radio controls.
region
Region is a large perceivable section on the web page.
row
A row of table cells.
rowheader
A table cell containing header information for a row.
search
This is the search section of a web document. This is typically a form used to submit search requests about the site or a more general Internet wide search service.
secondary
This is any unique section of the document. In the case of a portal, this may include but not be limited to: show times; current weather; or stocks to watch.
seealso
Indicates that the element contains content that is related to the main content of the page.
separator
A line or bar that separates and distinguishes sections of content.
slider
A user input where the user selects an input in a given range. This form of range expects an analog keyboard interface.
spinbutton
A form of Range that expects a user selecting from discrete choices.
status
This is a container for process advisory information to give feedback to the user.
tab
A header for a tabpanel.
tablist
A list of tabs, which are references to tabpanels.
tabpanel
Tabpanel is a container for the resources associated with a tab.
textbox
Inputs that allow free-form text as their value.
timer
A numerical counter which indicates an amount of elapsed time from a start point, or the time remaining until an end point.
toolbar
A toolbar is a collection of commonly used functions represented in compact visual form.
tooltip
A popup that displays a description for an element when a user passes over or rests on that element. Supplement to the normal tooltip processing of the user agent.
tree
A form of a list having groups inside groups, where sub trees can be collapsed and expanded.
treegrid
A grid whose rows can be expanded and collapsed in the same manner as for a tree.
treeitem
An option item of a tree. This is an element within a tree that may be expanded or collapsed

Note: when i have time to populate a dB, i will add a little ajaxian explanation as to the possible parents and children of each role. In the meantime, please visit WAI-ARIA Roles.

ARIA states and properties

Whereas roles are a static attribute of elements, states are properties that can change with user and server interactions. Properties include both dynamic states that need to be updated, and static properties, such as “required”.

Values for the ARIA States

busy
Indicates whether a live region is finished updating.
checked
The checked state indicates something has been rendered as being chosen by the user in the sense that it is a binary or tertiary operation. An example is a checkbox.
disabled
Indicates that the widget is present, but the value cannot be set and it cannot be internally navigated.
expanded
Indicates whether an expandable/collapsible group of elements is currently expanded or collapsed.
grab
This property is set to show an object’s state in drag and drop.
hidden
Defines whether or not the object is visible to the user.
invalid
Indicates that the element’s value is currently invalid, which discourages the form from being submitted.
pressed
Used for buttons that are toggleable to indicate their current pressed state.
selected
Sets whether the user has selected an item or not.

Values for the ARIA Properties

activedescendant
An element which has focus may specify its current active child. This is used when a element is responsible for managing its current active child to reduce the overhead of having all children be focusable.
atomic
Atomic is an optional property of live regions. When the region is updated, the atomic property is used to indicate if the assistive technology should present all or part of the changed region to the user.
autocomplete
Indicates whether user input completion suggestions are provided.
channel
This property specifies which channel should be used to present the updates for its associated live region.
controls
Defines the elements that are controlled by the current element.
datatype
Datatype defines the format type of an element.
describedby
Points to an element which describes the object.
dropeffect
This property is set for the target of a drag and drop operation to show the effect when the dragged object is released.
flowto
Establishes the recommended reading order of content, overriding the general default to read in document order.
haspopup
Indicates that element may launch a pop-up window such as a context menu or submenu.
labelledby
Points to the element which labels the current element.
level
Level is the hierarchical level of an element within a structure.
live
Describes the types of updates the user agent, assistive technology, and user can expect from an alert or live region of Web content.
multiline
Indicates whether a text box accepts only a single line, or if it can accept multiline input.
multiselectable
Indicates that the user may select more than one item from the current list.
owns
Defines an object as a parent of another document element, when the child does not appear directly in the subtree of the owner.
posinset
Indicates an item’s number or position within the current level of a tree or list.
readonly
Indicates that the widget is not editable.
relevant
Indicates the relevant areas of change within a live region.
required
Indicates that user input is required on the control before a form may be submitted.
secret
Provides the user with the ability to supply information to the system in a manner that makes it difficult for someone else (who may be watching) to discern the value that is being supplied.
setsize
The setsize property refers to the number of items in the current level of a list or tree.
sort
The sort property is used to indicate if items in a table or grid are sorted in ascending or descending order.
tabindex
Indicates tab order of elements. Elements with negative values are able to receive focus but are not included in the basic tabbing navigation list or cycle.
templateid
The templateid is a unique identifier, represented as a URI, for which an assistive technology may customize its user interface.
valuemax
Maximum allowed value for a range type of widget.
valuemin
Minimum allowed value for a range type of widget.
valuenow
The current value of a widget

Certain properties belong with certain roles. For example, autocomplete makes sense with the roles combobox and textbox. The value of the property or state is also limited to certain value types. In our autocomplete example, the value would need to be selected from a list of predetermined values, whereas a checkbox could have a state of invalid, disabled, required or checked, to name a few, with a bolean as the value.

Working with ARIA in Rich Internet Applications

ARIA and Live Regions

Live regions are sections of a web page or application that change dynamically either thru automatic updates or user interaction.
There are 5 properties specific for Live Regions:

atomic
indicate if the assistive technology should present all or part of the changed region to the user.
busy
has the live region is finished updating
channel
live
relevant

Politeness levels: Should ARIA intrude on the user on updates?

The value of the “live” state are expressed in terms of “politeness” levels. “Polite” regions notify of updates but do not interrupt users, and updates take low priority. A level of “rude” would indicate that the assistive technology should interupt the users current action to provide update information. A good example of using a polite level would be the ticker on a financial page — the user does not need to be interupted every 10 seconds to be informed as to whether a stock value has change. An example of a time to use a “rude” level is when the user has completed a step in a checkout process and the next step is visible. Values: Off, Polite, Assertive, Rude.

Validating your XHTML when including un-speced attributes

There is a tweak that you need to make in your XHTML page if you include ARIA: you need to use XHTML 1.1 and include the ARIA module in your header area. XHTML 1.0 does not support modularization. The ARIA States and Properties attributes will be understood by user agents in XHTML 1.0 by declaring and using the appropriate namespace the same as for XHTML 1.1, but such documents will not validate to the XHTML 1.0 DTD. None of the DTD snippets below enable validation, but I will update when the modules and/or specifications are updated. The first doctype listed is the HTML5 doctype, which will fully support ARIA when the spec is approved.

<!DOCTYPE html>
<DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1
    For Accessible Adaptable Applications//EN" "http://www.w3.org/2005/07/aaa/xhtml11-aaa.dtd">
<!DOCTYPE html PUBLIC "Accessible Adaptive Applications//EN"
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Strict//EN" "
   http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:aaa="http://www.w3.org/2005/07/aaa" lang="en">

Notes:

  • ARIA and HTML4: HTML 4.01 is non-extensible, so you can’t use namespaces for the property and state names. Please view the specs as they become available to see the HTML 4.01 support for ARIA.
  • ARIA and HTML5: Note that this post was originally written in 2008.  It is expected that ARIA will be fully supported as a module of the HTML5 specifications. HTML5 WHATWG ARIA spec

jQuery Tutorial: DOM Manipulation and sorting

JQuery is a lightweight JavaScript library that helps you quickly develop events, animations, and AJAX interactions.

In this tutorial we go over the following:

Note that the test javascript files associated with each section go with the same XHTML file.

Setting up your environment for this tutorial:


  • Download the JQuery library Generally you will want the minified version, but for today, download the uncompressed version so you can read some of the code if you so choose.
  • Save it locally in a directory (let’s call it “js” for this tutorial)
  • Create a new HTML page (Sample file)
  • Link to the JQuery file – <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
    You may need to change the 1.2.6 part to whatever the current release number is.
  • Create a new javascript file, and call it “myCode.js”
  • Link to your javascript file – <script type="text/javascript" src="js/myCode.js"></script>
  • Add some HTML to your page (this is what we’re going to manipulate).
  • You can also add some CSS.

ready method in anonymous function

The first step is to create an anonymous function withing your myCode.js file to encompass all of your javascript. If you take a look at your JQuery file, you’ll note that the entire file is in an anonymous function:

(function(){
 // code here

})();

All of your the code that you create should be included in it’s own anonymous function. This ensures that the jQuery variables are local: your variable declarations will not break the jQuery library, and the jQuery library will not overwrite your variables, methods and properties.

For our own javascript, we are going to encapsulate all our code in an anonymous function. However, since we are accessing elements of the DOM, we need to ensure that the DOM is loaded. We can’t use the parenthesis at the end as in the code above, which executes the anonymous function immediately, since our DOM isn’t loaded yet. We should only execute our anonymous function once we have the DOM. Without jQuery, and without much Javascript skill, the usual route is to include a document.onLoad event. Instead of using onLoad, which makes us wait until all the images are loaded, we’re going to use jQuery’s ready function — $(document).ready() — which executes when the DOM is ready.

The $(document).ready() function has advantages over other load time event handlers. Everything inside it will load as soon as the DOM is loaded, without having to wait for the page contents to be completely loaded. Ready is fired as soon as the DOM is registered by the browser, which allows for hiding and showing effects and other effects as soon as the user sees the page elements. Unlike the onLoad method, which is limited to only one function, the jQuery ready method allows for multiple functions to be loaded within it.

$(document).ready(function() {
 // code here
 });

Add the code above to your myCode.js file.jQuery

Targeting elements in the DOM with CSS and XPath

jQuery enables selecting elements with the same syntax that you would use to target that element with CSS. For example, we can target the first <h2> in our html file these two ways among others: (test js)

  • $("h2:first")
  • $("#mainContent > h2")

Take a look at the official jQuery Selectors page to get a better understanding of how you can use CSS syntax to target elements.

DOM Manipulation

The following are explanations and examples of the DOM manipulation methods provided by the jQuery core. The jQuery domentation for the DOM manipulation methods can be found at http://docs.jquery.com/Manipulation

jQuery’s version of innerHTML and textNodes

jQuery replaces innerHTML with the html() method to both return and set innerHTML with (and without) HTML elements. To return or set text, similar to retrieving and setting textNodes, use jQuery’s text() method. The main difference between the two involves the returning and rendering of HTML elements. (test js)

  • html()
    returns the HTML content of an element. This is directly equivalent to the innerHTML property commonly used by JavaScripters.
    var myHTMLContent = $("#mainContent").html(); // "<h2>My jQuery te.... (to) ...functionality</p>
  • html(myString)
    Sets the innerHTML for an element to myString.
    $("h2:first").html('This is new <em>header</em> content'); // changes the h2, and adds some emphasis
  • text()
    returns the text content, or text nodes, of an element without any markup as one string
    var myTextContent = $("#mainContent").text(); // returns same as html(), but without tags;
  • text(myString)
    Resets the text node value for an element to myString.
    $("h2:first").text('Ugly <em>header</em>); // escapes '>' and '<' instead of rendering italics

Child & Sibling nodes

append() and prepend() methods: similar to appendChild, except jQuery accepts a string, a DOM element, or a jQuery object as valid arguments. jQuery converts the argument into a text node or element depending on what is passed. (test js)

  1. $("#leftNav ul").append("<li>after the last &lt;li&gt;</li>"); // adds <li> at the end of <ul>
  2. $("#leftNav ul").prepend("<li>before the first &lt;li&gt;</li>"); // adds <li> at the start of <ul>
  3. $("#leftNav ul").append($("#mainContent h2")); // moves headers from the mainContent to the leftNav

  4. $("#leftNav ul").append($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav

There are two similar methods — appendTo() and prependTo() — which are basically inververted verstions of append() and prepend(). A.append(B) is about equal to B.appendTo(A)

Note: As shown in example 3, if you try to append an element that already exists in the DOM, that element will first be removed from DOM before being reinserted, or appended, in the new location.

before() and after() methods: similar to insertBefore() method (and the non-existant, but found in many javascript libraries, includeing this one, insertAfter()). The after() method inserts a node after a selected one. The before() method inserts a node before a selected one, like the javascript standard method of insertBefore().

  1. $("#leftNav ul").before("<h2>Left Navigation</h2>"); // adds header before the <ul>
  2. $("#leftNav ul").after("<h4>New Header</h4>"); // adds header after the <ul>
  3. $("#leftNav h4").before($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav before our new <h4>

There are two similar methods — insertBefore() and insertAfter() — which are basically inververted versions of before() and after(). A.before(B) is about equal to B.insertBefore(A)

Parent nodes

wrap(), wrapAll() and wrapInner() methods: wrap selected element or elements in another element. The argument can be an XHTML or DOM element as a string. If the element has child nodes, the element being wrapped will be put in the deepest child node of the first element. (test js)


  1. $("#leftNav ul").wrap("<div class=\"red\"></div>"); // the <ul> gets wrapped in a <div>
  2. $("#mainContent h2").wrap("<blockquote class=\"blue\"></blockquote>"); // the 2 <h2>'s get wrapped in a two separate <blockquote>s
  3. $("#mainContent h2").wrapAll("<blockquote class=\"blue\"></blockquote>"); // the 2 <h2>'s get wrapped in a single <blockquote>, moving the second <h2> up to be the nextSibling to the first <h2>
  4. $("#mainContent h2").wrap('<div class="shell"><div class="blue"></div><ul class="red"><li></li></ul></div>'); // puts the H2s in two "blue" divs, the LIs will be empty.
  5. $("#mainContent h2").wrapAll('<div class="shell"><div class="blue"></div><ul class="red"><li></li></ul></div>'); // puts the H2s in ONE "blue" div, the LI will be empty.
  6. $("#mainContent p").wrapInner("<a href=\"#\"></a>"); // puts an <a> between the <p> and the <p>'s first child.
  7. $("#mainContent").wrapInner("<blockquote class=\"blue\"></blockquote>"); // wraps all the children of #mainContent into one parent <blockquote>

remove() and empty()

remove(), empty() and replace() methods: similar to the native javascript removeChild() method, use remove() to remove element(s) from the DOM. Use the empty() method to keep the element, but remove the element’s children.
Note that remove() can take a parameter, but empty() does not. (test js)

  1. $("#leftNav li:first").remove(); // removes the first LI
  2. $("#leftNav li").remove(); // removes all the LIs from the #leftNav
  3. $("#leftNav li").remove(":contains('Second')"); //remove the LI containing the term.
    Note that the string is case-sensitive
  4. $("#mainContent h2:first").empty(); //removes the text in the first H2, but the h2 is not removed from the DOM
  5. $("#mainContent h2:contains('second')").empty(); //removes the text node child of the H2 containing the letters "second"

replaceWith(), replaceAll() and clone()

replaceWith() and clone() methods: Cloning creates copies of the DOM elements copied, including the new elements in the DOM, but does not append them to the page. To append the clone to the page, use one of the methods above.

  1. $("#leftNav li:first").replaceWith("<li>new first <em>LI</em></li>"); //text changed, LI is emphasized

  2. $("#leftNav li:first").text().replaceWith("new first <em>LI</em>");// grabs text, and replaces it. No <li> needed
  3. var navCopy = $("#leftNav").clone(); //copies it
    $("#mainContent").append(navCopy); //apends it

    The problem with cloning is that IDs are copied too, and ID’s need to be unique!


Effects with JQuery

The above was an overview of all the DOM manipulation functions. If you’re doing a simple site, those are likely all the javascript helpers you need. But, if that was all you could do with JavaScript, then you really wouldn’t need javascript libraries. The power of the libraries is in everything else they do for you. With jQuery you can create drag and drop, autocomplete, sorting, etc., the is unobtrusive and works cross browser in less than 10 lines of javscript. Proof? Here are two examples:

Sorting a table with javascript:

  1. Create a table in plain old XHTML, and populate that table with data. Give your data table the class of sort with: (sampleFile)
    <table class="sort">
  2. Download the jquery libary and the jquery.tablesorter.js file.
  3. Attach the two jQuery files and your own JavaScript file to your XHTML file by including the following in the header of your XHTML file:
    <script type="text/javascript" src="jquery-1.2.6.js"></script>
    <script type="text/javascript" src="jquery.tablesorter.js"></script>
    <script type="text/javascript" src="myTableCode.js"></script>
  4. In your JavaScript file (called myTableCode.js above) include the simple script:
    $(document).ready(function() {
        $("table.sort").tablesorter();
     });
  5. Literally, the previous step is all there is to sorting tables bu column content in However, that just sorts it based on the content of the HTML. So, if you have an <em> or <p> in one table cell and not in another, it may not sort the way you want. To sort based on a portion of your code inside a cell, use the textExtraction utility provided by jQuery:
    $(document).ready(function() {
    
     $("table.sort").tablesorter({
            // define a custom text extraction function
           textExtraction: function(node) {
                // if there is a link, return the content of the link
    		if(node.getElementsByTagName('a')[0]){
    				return node.getElementsByTagName('a')[0].innerHTML;
        			}
            return node.innerHTML;
            }
        });
     });

See my example

Making a list sortable

Similar to the sortable table, you can make a make a list that is sortable by dragging list items around. (example)

  1. Create a list, give it the class of “sortable”.
    <ul class="sortable">
      <li>This is my first list item</li>
      <li>second list item</li>
      <li>Brief 3</li>
      <li>Long 4</li>
    </ul>
  2. Go to the jQuery Download Builder and select “sortable”. You’ll note that the other required library elements are automatically selected.
  3. Attach the three javascript files downloaded from the builder, and your own javascript file, to your page with the list.
    $(document).ready(function() {
         $("ul.sortable").sortable();
       });

Userful Links

JavaScript Objects

Javascript: Things you should know

Note: This is part III of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over objects at a very basic level. Most books cover objects in a confusing manner. Below are really simple examples which, if you have been confused, will hopefully make things make sense. The previous entry was JavaScript Switch Statement Quirks.

JavaScript Objects Demystified

Everything in JavaScript is an object except core types. true, false, null, undefined and numeric values are not objects. Strings, with the length property and numerous methods, are objects.

Most JavaScript objects are collections of name-value pairs. I think of objects as associative arrays. The "name" or key of an object is a string except for in the array object where it can be a string or a incremental integer. The value can be any JavaScript value, including an array or other object.

Creating a JavaScript Object

There are two basic ways to create an object which are semantically equal. You can declare an object using an object function and instantiate the object by using the "new" keyword or you can use the object literal method:

  • var obj = new Object();
  • var obj = {}; // object literal method

Assigning properties to an object

An object’s properties can be assigned with the dot operator or like an associative array::

obj.name = "Estelle";
obj["name"] = "Estelle";

the property values can be retrieved in a similar fashion

var myname = obj.name;

var myname = obj["name"];

The difference between using the dot operator versus the array method is that since the key value is a string, you can use reserved words for the "name". If you plan on creating property names based on user input, this can be aspirin for what otherwise would be a headache. Otherwise, the dot syntax is easier, and reserved words should not be used. Using a reserved word is a bad idea. Both the object name and property name are case sensitive.

obj.for = "Estelle"; // produces an error
obj["for"] = "Estelle"; // allowed

Object Literals

Object literal syntax can be used to initialize the entire object.:

var obj = {
  name: "Estelle",
  gender: "Female",
  outfit: {
     top: "t-shirt",
     bottom: "jeans",
     shoes: "hiking boots"
     }
}

You can chain it together:

obj.outfit.shoes; // hiking boots
obj["outfit"]["bottom"]; // jeans

Even though outfit in the example above seems like it is a newly created object within obj, it isn’t:

outfit.shoes; // error, since outfit is not defined
obj.shoes; // undefined, not an error, since obj is defined, but the property shoes has not been assigned a value

Assigning methods to an object

Methods are simply functions tied to objects. For example, toUpperCase is a method of the string object. The simplest way to attach a method to an object is to use an anonymous function:

var greeting = {
  name: "Estelle",
  message: "this was written by ",
  welcome: function(){
     alert("Objects now make sense");
     },
  sayhi: function(){
     alert(this.message + this.name);
    }
}

welcome is a method of the greeting object. Calling greeting.welcome();, with the parenthesis, will cause the alert.

sayhi is also a method of the greeting object. Calling sayhi.welcome();, with the parenthesis, will cause the alert. The this keyword refers to the object that is calling the function, and will be discussed in further detail in a future entry.

Method names are also case sensitive.

the Window object.

All variables that are not assigned as properties of other objects become properties of the window object.

var animal = {};
var myCat = animal.pet = "Sassafrass";

In this case, animal is an object, pet is a property of the animal object and myCat is a property of the window object.

The following all work and return "Sassafrass":

  • animal.pet;
  • window.animal.pet;
  • myCat;
  • window.myCat;

The following may not return what you expected:

  • pet; // throws an error as pet is a property of the animal object, not the window object
  • window.pet; // undefined
  • window.animal // evaluates to object.

Note: JSON, or JavaScript Object Notation, is a subset of JavaScript’s oject literal notation.

JavaScript Object Properties and Methods

All objects in javascript inherit from the Object object, and therefore inherit the properties and methods of Object, including:

  • constructor property
  • prototype property
    used to assign new properties and methods to future instances of the object type.
  • hasOwnProperty() method
  • isPrototypeOf() method
  • propertyIsEnumerable() method
  • toString() method
  • toLocaleString() method
  • valueOf() method

Extending Objects

It is fairly simple, though not always necessary, to extend objects with new methods and properties. Use the protoype property, inherited from the Object object to add methods to an object. Here are some examples of String, Array and Date object methods.

String.prototype.capFirst = function(){
   return this.charAt(0).toUpperCase() + this.substr(1);
}

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

Array.prototype.sortCaseInsensitive = function(){
    return this.sort(function(a,b){ return (String(a).toLowerCase() > String(b).toLowerCase())? 1: -1;}
}


Date.prototype.customFormat = function(formatString){
  //The code for this is in the javascript date object article.
}