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:

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>....</li>
</ul>

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

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 (For descriptions, roll over the items below)

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

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:

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

This section is not finished
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:


xmlns:aaa=”http://www.w3.org/2005/07/aaa” lang=”en”>

Notes:

  • ARIA and HTML: 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.

Note: This blog is still in development, but it’s come a long way, and it is likely already a bit helpful. I will be adding more example snippets and more about live regions and handling dynamic changes, so come back next week if you want to read more. The original post was 03/12/08 but I've reposted it since WAI-ARIA is finally being better supported by YUI, Dojo, jQuery, IE8, Safari 4, and other browsers.

Posted in Accessibility, AJAX, Best Practices, Web Development | 1 Comment

CSS Browser Support (iPhone, IE8, IE7 Compliance Mode, FF 3.5 beta & Safari 4 Beta included)

Note: This article is about CSS selectors. I also have a post on All CSS2.1 Properties and Values, and Broswer Support (huge file, but worth the download time)

Update 6/30/09: Firefox 3.5 was released today. Like Safari 3.1 and newer (including Safari 4 beta), Opera 9.64 and newer and Google Chrome all support ALL CSS2.1 and CSS3 selectors. Here is a breakdown of all the browsers I’ve tested:

  • Green / √ means current support.
  • Orange / Δ means that the browsers have some support for the selector.
  • Red / Χ means that the browser is non-compliant.


CSS Selectors and Browser Support

See also: CSS Properties & Values

Browsers
Pattern Meaning IE6 IE7 IE8 FireFox Safari Opera NetSc CHROME
E:active

E:hover

E:focus

Dynamic pseudo-classes

Matches E during certain user actions.

Δ Δ
Δ Δ
Χ Χ
E:before

E:after

Static pseudo-classes
See generated content
Χ Χ
Χ Χ
iPhn Windows XP Mac OSX
Selector Saf 3.2 Saf 3.0 goog chrm FF 3.5 FF 3.0 FF 2.0 FF 1.5 Op

9.0

Saf

3.0

IE8

IE7 in IE8

IE7 IE6 Saf 4 beta Saf 3.2 Saf 3.1 Saf 1.3 Op 9.64 FF 3 FF 2 NS 7.1
*
E
.class Δ
#id
E F
E > F Χ
E + F Χ
E[attr] Δ Δ Δ Χ Δ
E[attr=val] Δ Δ Δ Δ Δ Χ Δ Δ Δ
E[attr~=val] Δ Δ Δ Δ Δ Δ Χ Δ Δ Δ
E[attr|=val] Δ Δ Δ Δ Δ Δ Χ Δ Δ Δ
:first-child Δ Δ Δ Δ Δ Δ Δ Χ Δ Δ
:link Χ
:visited Χ
:lang() Δ Χ Χ Χ Χ
:before Χ Χ Χ Χ
::before Χ Χ Χ Χ Χ
:after Χ Χ Χ Χ
::after Χ Χ Χ Χ Χ
:first-letter Χ
::first-letter Χ Χ Χ Χ
:first-line Χ
::first-line Χ Χ Χ Χ
The following selectors are new to CSS3 (above were in previous versions)
E[attr^=val] Δ Δ Δ Χ Δ Χ Χ Χ Δ Δ Δ
E[attr$=val] Δ Δ Δ Χ Δ Χ Χ Χ Δ Δ Δ
E[attr*=val] Δ Δ Δ Δ Χ Χ Χ Δ Δ Δ
E ~ F Χ Χ Χ
:root Χ Χ Χ Χ Χ
:last-child Χ Δ Δ Χ Χ Χ Χ Χ Χ Χ Δ Δ
:o nly-child Χ Δ Δ Χ Χ Χ Χ Χ Χ Χ Δ Χ
:nth-child() Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:nth-last-child() Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:first-of-type Δ Χ Χ Χ Χ Δ Χ Χ Χ Χ Χ Χ Χ Χ
:last-of-type Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:o nly-of-type Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:nth-of-type() Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:nth-last-of-type() Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ Χ
:empty Χ Δ Δ Χ Χ Χ Χ Χ Χ Χ Δ Δ
:not() Χ Χ Χ Χ Χ
:target Χ Χ Χ Χ Χ
:enabled Χ Χ Χ Χ Χ Χ
:disabled Χ Χ Χ Χ Χ Χ
:checked Χ Χ Χ Χ Χ

IE8 CSS Selector Support

IE8 Supports the CSS2.1 selectors, including pseudoclasses but not pseudo elements. (See Double Colon Notation). IE8 has support for has support for Accessible Rich Internet Applications (ARIA)

To force IE8 to render your page in IE8 compliance mode, include the following meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

IE7 within IE8 CSS Selector Support

The CSS selector support of IE7 within IE8 (when IE8 displayes a page in IE7 compatibility mode) is identical to IE7 as a standalone. However, the CSS properties do render differently. I will have to blog about that in a seperate entry when I get around to garnering all the differences.

IE7 within IE8 understands the IE7 star hack. Because the CSS renders differently even though the selector support is the same, it may take a bit before I figure out the best filter.


iPhone

The original version of the iPhone came with a Safari browser that did not support all CSS3 selectors. The currently active version of Safari on the iPhone does support all CSS3 selectors. The grid below has been updated to reflect that. I have kept the old version of the iPhone CSS3 support just in case you want to support "unlocked" version of the iPhone, that do not get updated as often. Personally, I assume all iphones hitting my apps support all CSS3. For more information on iPhones, see iPhone CSS Support

Safari 4 Beta CSS Selector Support

Safari 4.0 Beta was released Feb. 24, 2008. Since Safari 3.2 supported all CSS selectors, this Safari 4 part of the post may be a bit mute. Safari 4 beta also supports ARIA and for CSS effects, animation and canvas. It also seems to have many more native debugging tools native to the application (or maybe what I see is a carry over from the tools I installed in my previous version of Safari). Safari 4 is Acid 3 compliant!

IE8 Notes:

  • E[attr]Does not match the attribute when the attribute value is empty or not written correctly.

IE7 within IE8 Notes:

  • E[attr] Same as IE8, does not match the attribute when the attribute value is empty or not written correctly.
  • E[attr~=val]Only issue is that for this selector to work, the value of the attribute is case sensitive
  • E[attr|=val]IE7 has some case sensitivity issues, but generally works.
  • :first-child IE7 considers a comment or a text node as a first-child, when it shouldn’t: only elements should be considered children. So, IE7 matches the first comment instead of the first child. If it sees text or a comment as the first child, it will not consider the first element as the first child.
Posted in Web Development | 7 Comments

Canonical tag for SEO


Google, Yahoo and Microsoft are now supporting the canonical meta tag as the standard for identifying the actual source of your content: the real URL that you want to recieve page rank for your key terms.

Many sites have the same content show up with different URLs due to search features, dynamically generated URLS, tags, etc. Google, Yahoo and other search engines have been knocking your sites for having duplicate content as if you were spamming your terms. In other words, having multiple URLs pointing to the same content has been hurting your page rank and your site.

Now you have a way to make sure that your multiple content helps you instead of hurts you.

Implementing the CANONICAL meta tag

  1. Pick one URL for your page – “the pretty, preferred or canonical URL” (to quote Matt Cutts). For example, this page’s main, or canonical, URL is http://www.evotech.net/blog/2009/02/canonical-tag-for-seo/, though you may find it thru http://www.evotech.net/blog/?p=69 or http://www.evotech.net/blog/?s=SEO, http://www.evotech.net/blog/category/seo/ or simply http://www.evotech.net/blog.
  2. Figure out how to include your page’s main URL in pages that are dynamically generated. For example, I need to figure out how to include my primary URL – http://www.evotech.net/blog/2009/02/canonical-tag-for-seo/- in the web page showing this content no matter which URL from the bullet point above is shown.
  3. Once you know how to get the URL you picked in step 1 into your possible other pages feeding the content from your main URL, place the canonical link tag inside the tag with the main content’s URL. For this example, I would place: <link rel=”canonical” href=”http://www.evotech.net/blog/2009/02/canonical-tag-for-seo/” /> in my header.

The syntax is similar to the stylesheet link tag:

<link rel=”canonical” href=”http://www.yourdomain.com/yourpage” />

The canonical tag is ONLY for webpages in the same domain. So, http://evotech.net/blog pointing to http://blog.evotech.net or http://www.evotech.net/blog is fine. However, I can’t point http://estelleweyl.com/blog to http://evotech.net/blog if I were to have that URL as an addon domain on this server.

Now I just have to figure out how to do step 2 so I can create canonical links for this blog.

Added Notes:

Lori basically figured it out for us: (copied from http://beedragon.com/wp-test-site/2009/02/13/add-canonical-link/). Thanks!

Add canonical link tag to head

<?php if ( is_single() || is_page() ) { ?>
<link  rel="canonical" href="<?php the_permalink(); ?>" />
<?php } ?>

Occurs to me now that you’d have to hardcode main url, then get the slug and other url info dynamically:

<?php if ( is_single() || is_page() ) { ?>
<link rel="canonical" href="http://mainurl.com/<?php echo the_time('Y'); ?>/<?php echo the_time('m'); ?>/<?php echo the_time('d'); ?>/<?php echo $post->post_name; ?>" />
<?php } ?>

There is probably a prettier and/or more efficient way to do that, but can’t think of one at the moment.


Posted in Best Practices, SEO, Web Development | 7 Comments

hover pseudoclass for the iPhone

Since you’re not hovering, there is no hover pseudo class on the iPhone. instead they have touch events. To simulate the :hover pseudo class, include javascript similar to this:

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
   myLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
   myLinks[i].addEventListener('touchend', function(){this.className = "";}, false);
}

and in your CSS add something similar to:

a:hover, a.hover { /* whatever your hover effect is */ }

Notes:

  • onTouchStart is similar to onMouseOver and onTouchEnd is similar to onMouseOut
  • You’ll likely want something more complex than simply removing the class on touch end. This is just a very simple example that will replace all classes on all your links with a "hover" class, which is probably not what you want. But you get the idea.
  • You can use this on all elements, not just links.

-Estelle Weyl

Note:

Posted in Best Practices, CSS (including hacks), HTML, IE7, iPhone, JavaScript, Web Development | 8 Comments

Browser Testing: 3 tools you can’t live without

Firefox 2 and Firefox 3 don’t render the same. Also, Firebug 1.0 is less buggy than Firebug 1.2. So, at this point, it really is necessary to run multiple versions of Firefox in your development environment, similar to how most of us have been running IE6 and IE7 on the same machine for years. What? You haven’t been running IE6 and IE7 on the same machine? Didn’t know it was possible? Here are three tools or links that you need to check out if you do any cross browser testing (which I hope you do).

Here are some links to help you out:

  • Multiple Firefox: I have both FF2 and FF3 installed on my laptop. I develop in FF2 with Firebug 1.0, and have FF3 with FB1.2 for testing. Instructions for running multiple Firefox apps on the same box can be found here: http://jeroencoumans.nl/journal/multiple-firefox-versions.
  • IE6 on Mac/ IE6 on Linux: I have a mac, so for quick IE6 checks I have IE6 installed in my Mac OSX. This isn’t a perfect rendition of IE6, but it’s good enough for quick tests, not final QA. To install IE6 on your mac, go to http://www.kronenberg.org/ies4osx/
    . I also sometimes work on Ubuntu 9.04 (a linux box), and have IE6 for Linux installed.
  • Multiple IEs: To install IE7 and IE6 on your PC, or in your Parallels or VMWare Windows environment on your mac, you must install IE7 as your main IE application, and then you can go to http://tredosoft.com/Multiple_IE to install earlier versions – IE6, and even earlier.It does not support IE7, which is why IE7 (or IE8) needs to be a regular installation. Multiple IEs does NOT work on Vista.

Unfortunately there are a few quirks with running MultipleIE and IE6 on Mac- but I would say MultipleIE matches the crappiness of IE6 at about 99.9%.

These are links that I am always forwarding to people, so I figured I would finally blog them. Cheers!

-Estelle Weyl

Posted in Browsers, firebug, IE7, Web Development | 3 Comments

XHTML Elements, their parent, children, attributes and default browser presentation

XHTML Elements, their meaning, semantics and attributes
<ELEMENT> Element Name Block, Inline, etc. Element’s Parents Element’s Children 3 Browser Presentation

Attributes1

Comments
Elements occuring outside the body element
<!DOCTYPE> Document Type Declaration Not Displayed first line none -   Required. Should be first in the document
<html> html   root element <head> and <body> - xmlns Required
<head> document head Not Displayed <html> <base>, <link>, <meta>, <style>, <script>, <title> other than the title, all the other child elements are not visible to user profile, id, dir, lang. NOT class, style, title Required
<base /> url base for links Not Displayed <head> Empty3 - href, no standard attributes1  
<link /> link Not Displayed <head> Empty3 - href, charset, hreflang, type, rel, rev, media  
<meta /> meta Not Displayed <head> Empty3 - content, name or http-equiv, scheme  
<style> style Not Displayed <head> text - type, media  
<script> script Not Displayed <head> (allowed in <body> too. text or src attribute, not both - type, charset, src, defer do NOT self close with slash. Use end tag
<title> document title   <head> text only seen in the chrome of browser id, dir, lang. NOT class, style, title Required
Elements Occuring in the <body>
<body> document body block <html> Block3   all non-core attributes are deprecated Required
<a> Anchor inline inline or semantic block Text and inline3 except <a> underlined and colored href, hreflang, rel, charset, type, name, rel, rev, shape (rect), coords cannot contain other <a> children

<abbr>

Abbreviation inline inline or semantic block only text / inline3 dotted underline with cursor, tooltip title  
<acronym> acronym inline inline or semantic block only text / inline3 dotted underline with cursor, tooltip title  
<address> address blocktext <blockquote>, <div>, <body>, <form> inline3 elements, <p> italic, block -  
<area /> image map area Not Displayed <map> Empty3 makes hot areas on image alt, shape, coords, href, nohref ‘rect’ is default shape if omitted
<bdo> bi-directional override inline inline or semantic block only text / inline3 reversed text dir, lang  
<blockquote> long quote blocktext   block3 margin: 1em 40px; cite  

<br />

break return or forced line break inline   none line-break does not take internationalizaion attributes use as linebreak in poetry or addresses, not to separate paragraphs.
<button> push button inline   any inline3, except form elements and <a> push button disabled, name, type 2, value, accesskey, tabindex Cannot contain <input>, <select>, <textarea>, <label>, <button>, <form>, <fieldset>, <iframe> or <isindex> as children.
<caption> caption   <table> text and inline3 centered above table - must be first child of the table
<cite> citation inline phrase element text and inline 3 italicized text - -
<code> code inline phrase element text and inline 3 monospace font - -
<col /> column Not Displayed <table> Empty3 - char, charoff, span align & valign allowed, but use CSS instead
<colgroup> column group Not Displayed <table> zero or more <col>   span, char, charoff. align & valign allowed, but use CSS instead while empty, close with an ending </colgroup> tag.
<dd> definition description block <dl> Flow3 indented with a left margin - -
<del> delete inline or block inline or block Flow3 strikethrough cite, datetime don’t put block content in a <del> that is inline

<dfn>

definition inline phrase element only text italic - -
<div> generic block element block   Flow3 - - -
<dl> definition list lists (block)   one or more <dd> and <dt> only - - -
<dt> definition term block <dl> text and inline3 only - - cannot have block elements as children!
<em> emphasized text inline phrase element text and inline3 only italics - -
<fieldset> field set block <form> <legend>, Flow 3 box around child elements with legend, if any - -
<form> form Block block element block elements and block form elements - action, method, enctype, accept, accept-charset cannot nest a <form> within a <form>
<h1-6> headers heading (block) body or block inline and text varying font sizes and bold - -
<hr /> horizontal rule blocktext (block) body or block Empty horizontal line - -
<iframe> internal frame         longdesc,
name,
src,
frameborder,
marginwidth,
marginheight,
scrolling,
align,
height,
width
 
<img /> image inline inline or semantic block Empty The image identified in the src src, alt, longdesc, usemap, ismap height and width are optional attributes best omitted.
<input /> input inline inside a semantic block located in <form> Empty depends on type type, name, value, check, disabled, readonly, size, maxlength, src, alt, usemap, accept type defaults to text if not declared, but you should declare it
<ins> Insert inline or surrounding blocks   Flow underlined cite, datetime don’t put block content in a <del> that is inline
<kbd> keyboard inline phrase element text (and inline) monospace font - should really just be text
<label> label inline semantic block within a <form> text and inline - for, accesskey cannot contain child <label> elements
<legend> caption for fieldset   <fieldset> inline and text top left section of the fieldset box -  
<li> list item block <ul> or <ol> Flow bulleted new line -  
<map> image map Not Displayed   one or more <area> OR block - ID, name  
<object> object     <param>, if included, should come first. Flow   declare, classid, codebase, date, type, codetype, archive, standby, usemap, name, tabindex allowed in <head> by spec. height and width are optional attributes best omitted.

<ol>

ordered list lists (block) block one or more <li> elements indented <li>s with numeric bullets -  
<optgroup> option group   <select> one or more <option> bold, non-selectable header for a group of indented options. label, disabled  
<option> option   <select>, or within <optgroup> textnode appears within the select drop down as new row selected, disabled, label, value if value is omitted, submitted value is the text node value
<p> paragraph block block inline and text new line of text - -
<param /> parameter invisible <object> none not visible, though may cause visual effects id, name, value, valuetype, type can place params as name/value pairs in the object element
<pre> preformatted text blocktext (block)   inline, except <img>, <object>, <sub> & <sup> monospace font and nowrap whitespace - Cannot contain <img>, <object>, <sub>, or <sup> elements
<q> inline quotation inline inline or semantic block inline and text quotes at start and end of content cite (URL) quote style depends on language. Poor browser support of quotes
<samp> sample computer code inline phrase element inline monospace font - -
<select> option selector inline inline or semantic block within <form> one or more <option> required, optional <optgroup> drop down list name, size, multiple, disabled, tabindex  
<span> span (generic non-semantic container) inline inline or semantic block text or inline - -  
<strong> strong emphasized text inline phrase element text or inline bolder text - don’t use in <h1-6> as those are already emphasized
<sub> subscript inline inline or semantic block text or inline smaller, subscripted text - do not include in <pre>
<sup> superscript inline inline or semantic block text or inline smaller, superscript text - cannot be a child of <pre>
<table> data table block block or body <caption>?, (<col>*|<colgroup>*), <thead>?, <tfoot>?, (<tbody>+|<tr>+)) 4 data table summary (width, border, frame, rules, cellspacing, cellpadding)

width, border, cellspacing, cellpadding are allowed, but better to use CSS.

 

<tbody> table body block <table> one or more <tr> appears between thead and tfoot char, charoff in code flow, comes AFTER <tfoot>
<td> table data cell block <tr> Flow vertical align middle, text-align: left abbr, axis, headers, scope, rowspan, colspan,
width, align & valign allowed, but use CSS instead
 
<textarea> text area block <form> or block within form textnode or no text multi-line text field displaying textnode if there is one rows, cols, name, disabled, readonly  
<tfoot> table footer block <table> only one or more <tr> appears at bottom of table char, charoff, width, align & valign allowed, but use CSS instead comes before <tbody>
<th> table header cell block <tr> only Flow bold and center abbr, axis, headers, scope, rowspan, colspan, char, charoff. width, align & valign allowed, but use CSS instead  
<thead> table head block <table> only one or more <tr> only at top of table char, charoff. width, align & valign allowed, but use CSS instead follows opening <table> or <caption> if there is one.
<tr> table row block <table>, <thead>, <tfoot> or <tbody> one or more <th> or <td> new line char, charoff. width, align & valign allowed, but use CSS instead if any of the parent elements are present, there must be at least one <tr>
<ul> unordered list lists (block) block one or more <li> elements indented, bulleted on <li>s - -
<var> variable inline phrase element text (and inline) italic - No reason to include inline elements. Should be just text as child
Elements you should not be using, that are still valid
<tt> teletype inline inline or semantic block text (and inline) monospace - Purely presentational. Should be deprecated, but aren’t yet.
<i> italic italic
<b> bold bold
<big> big font bigger font
<small> small font smaller font
<frame /> frame block <frameset> Empty page within a page

name, src, longdesc, security. frameborder,
marginwidth,
marginheight,
noresize,
scrolling also allowed.

only allowed in frameset DTD
<frameset> frameset block <body> <frame>, <frameset>, <noframes> divides the browser window cols, rows. only allowed in frameset DTD
<noframes> no frames block <frameset> Flow - - can be found outside of frameset (for no iframe support)
<noscript> no script block Flow Flow - - Your site should work without scripts, so should not be necessary

Note:

  1. Attributes: All elements accept the standard and internationalization attributes of id, class, title, style, dir, and lang unless otherwise noted. The attributes column lists elements specific attributes and exceptions to the core attributes. Required attributes have been emphasized.
  2. Even though the type attribute is not required by the specifications, always define type because IE is stupid.
  3. Inline: <a>, <br>, <span>, <bdo>, <map>, <object>, <img>, <tt>, <em>, <strong>, <dfn>, <code>, <q>, <samp>, <kbd>, <var>, <cite>, <abbr>, <acronym>, <sub>, <sup>, <input>, <select>, <textarea>, <label> and<button>
    Block:
    <p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <ul>, <ol>, <dl>, <pre>, <hr>, <blockquote>, <address>, <fieldset>, <table>
    Flow: text < form > and all the inline and block elements
    Empty: self closing element, include a slash before the end of the opening tag to self close. Contains no children
  4. Table elements: 0 or 1 optional <caption> element, 0 or more optional <col> elements OR 0 or more optional <colgroup> elements, 0 or 1 optional <thead> element, 0 or 1 optional <tfoot> element, and REQUIRED either one or more <tbody> elements OR one or more <tr> elements.
Posted in Browsers, DTD, HTML, Web Development | 3 Comments

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 ncloe()

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

Posted in JavaScript, Web Development | 7 Comments

15 JavaScript Gotchas

We all know that JavaScript can trip you up. Here are a 15 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 15 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
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

dt {font-weight:bold; font-size:116%;}

Posted in Best Practices, JavaScript, Web Development | 7 Comments

http-equiv: Meta Attribute Values for http-equiv

The http-equiv attribute is used by servers to gather information about a page using the HTTP header. The meta tag’s http-equiv attribute set is similar to a http header. The attribute lets you to send additional information to the browser in the http header. I rarely use any http-equiv meta elements other than content-type, and had never really thought about them for any purpose other than caching, So, as I looked deeper into the possible values, I thought I would “share”. There isn’t as much depth to this post as my usual endeavors, but hopefully this will make a good resource to bookmark.

Structure of Meta Element

The structure of the meta element is:

<meta http-equiv="value" content="value" />

Do not include the name attribute in the meta when the http-equiv attribute is included.

Do include the content attribute. Below are the various values for the http-equiv attribute:

Values for http-equiv

<meta http-equiv=”content-type” content=”type; charset=charset” />
http-equiv=”content-type” indicates the type of data sent to the browser, enabling the browsers to know what to do with data received. The <meta> element, in all its forms, are optional. Content-type is the one you really don’t want to omit. For English sites use <meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />. There are many other possible values for content, such as <meta http-equiv=”content-type” content=”text/html; charset=ISO-2022-JP” /> for Japanese sites.
<meta http-equiv=”expires” content=”date” />
The date indicates the date and time that the document is set to expire. When the date is reached, the document will be reloaded even if the document is stored in the cache. This <meta> element is used to disable caching of the document: simply put a date that has passed in the date, and this will cause the browser to fetch new files. Put a date far into the future if you want the page to be cached. Note that IE6 will fetch the content of a users home page when a new browser window is opened, even if you set it to cache.

<meta http-equiv=”set-cookie” content=”name=value; expires=date; path=url“” />
The name is the name of the cookie.The value is the value to be set for that named cookie. The date is the date and time when the cookie will be deleted from the the computer. The date is optional. If you don’t include an expiration date and time, the cookie will be deleted when you exit the browser. You can include more than one http-equiv=”set-cookie” if you need to set more than one cookie name/value pair.
<meta http-equiv=”content-encoding” content=”data encoding” />
Indicates the encoding of the returned data; usually the compression type. For g-zipped documents, use <meta http-equiv=”content-encoding” content=”gzip” />
<meta http-equiv=”allow” content=”methods” />
Supposedly you include methods supported by server, but I’ve never seen this in action.
<meta http-equiv=”date” content=”date” />
Include the date and time that the page was created.
<meta http-equiv=”last-modified” content=”date” />
The content is the date and time the page was last modified.
<meta http-equiv=”location” content=”n; url” />
<meta http-equiv=”refresh” content=”n;url=url” />
ex. <meta http-equiv=”refresh” content=”12″ />
ex. <meta http-equiv=”refresh” content=”3;url=http://www.evotech.net/blog” />n is the interval at which time the page should be refreshed: in our example, the page will refresh every 12 seconds. If included, url is the location the page will redirect to. Our second example would cause the page to redirect to Community MX after 3 seconds. Please do NOT use this method to redirect to a new URL. It is not accessible.

<meta http-equiv=”window-target” content=”location” />
The http-equiv=”window-target” specifies the “named window” of the current page. The main use is to prevent a page from appearing inside another framed page: <meta http-equiv=”window-target” content=”_top” />. Usually this means that the Web browser will force the page to go the top frameset.

<meta http-equiv=”www-authenticate” content=”" />
http-equiv=”www-authenticate” is one method of providing basic access authentication, but providing such authentication in such a visible manner is not recommended for security reasons.
<meta http-equiv=”pics-label” content=’labellist‘ />
The Platform for Internet Content Selection (PICS) is a standard for labeling online content: basically online content rating. To generate the labelist, visit safesurf or another labellist generator. Note that the content attribute uses single quotes, because the PICS label syntax uses double quotes.

<meta http-equiv=”pragma” content=”option” />
<meta http-equiv=”cache-control” content=”option” />
You can use the http-equiv=”expires” with a past date to ensure that the browser retrieves fresh files from the server (rather than caching). Since not all client browsers and caching devices (e.g. proxy servers) are known to successfully implement all no-caching options, include multiple no-caching options, including:

<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="cache-control" content="no-store" />
<meta http-equiv=”content-language” content=”language-Country” />
Enables language specification, enabling search engines to accurately categorize the document into language and country. The language is the main language code, and the country is the country where the dialect of the language is more specific, such as en-US versus en-GB, US English versus English spoken in Great Britain. <meta http-equiv=”content-language” content=”de-AU” /> would be German as is spoken in Austria.

<meta http-equiv=”content-script-type” content=”language“>
The default script language for the script element is javascript. If you aren’t using JavaScript as your default, declare <meta http-equiv=”content-script-type” content=”text/VBscript”> informs the browser which type of scripting language you are using by default: is this case, Visual Basic.

<meta http-equiv=”page-enter” content=”revealtrans(duration=seconds,transition=num)” />
<meta http-equiv=”page-exit” content=”revealtrans(duration=seconds,transition=num)” />
Page-enter and page-exit are Microsoft proprietary transitions that only work in Internet Explorer. The seconds is how long the transition should take, and num is an integer between 0 and 23, correlated with a specific type of transition (23 is random).<meta http-equiv=”page-enter” content=”revealtrans(duration=2,transition=6)”>. There are 23 transitions, from 0 – 22. A transition with value of 23 is allows Internet Explorer to randomly select from the 23 available transitions. <meta http-equiv=”page-enter” content=”blendTrans(duration=sec)” /> is another value.

<meta http-equiv=”imagetoolbar” content=”no”>
Another IE specific (which means you shouldn’t use it) http-equiv value is “imagetoolbar”. In some versions of Internet Explorer, when an image is hovered, an image toolbar appears. <meta http-equiv=”imagetoolbar” content=”no”> enables the disabling of the image toolbar.

Notes:

  • The following characters appearing within the content must be escaped using SGML entities:
    single quote
    & & ampersand
    > > greater than
  • Note: Dates take the following format:
    Thu, 25 Nov 2008 16:15:30 GMT
Posted in Browsers, HTML, Web Development | 9 Comments

CSS Hack for Google Chrome and Safari 4

Valid CSS filter targeting Google Chrome and Safari 4

To target only webkit, which includes Google and Safari, encompass all the CSS that you want to use just to target Webkit in the following @media block:

@media screen and (-webkit-min-device-pixel-ratio:0) {
.myClass { background-color: #FF0000; }
#myId {color: #0000FF;}
p, a, li {text-shadow: 3px 3px 3px rgba(0, 0, 0, 0.4);
}

The rest of this post is outdated.


NOTE: WHAT IS BELOW IS OLD, AND NOW TARGETS Opera, Firefox, Safari and Chrome.

NOTE: This was written in 2008 for Safari 3.1 and the original release of Chrome. This is NO LONGER VALID as a filter, since, like all forward thinking filters, it now targets all the modern browsers that support CSS3 Selectors.

Non-compliant selectors can be used and a valid way to target individual browsers. Chrome supports every selector, just like Safari 3.1. My recommendation is to use the body:first-of-type hack, the CSS hack/filter for Safari as a filter for Safari 3+ and Chrome. There should be no reason to target Chrome with the exclusion of Safari 3.1, but if you want to target both, filtering out Safari 3.0, I would try using:

body:nth-of-type(1) p{
   color: #333333;
}

Only the Google Chrome and Safari 3.1 browsers will show paragraphs as grey. The logic is:

  • web pages only have one body element
  • only those two browsers support the pseudo-class of :nth-of-type()
  • body:nth-of-type(1) will match the first, and only, body element.

Use it as a predecessor to more specific selectors targeting the body’s children.

Note: as more browsers become more standards compliant, they will understand this code as well. IE6, IE7, IE8 will never understand it. Newer versions of Safari, Chrome and Firefox will.

Posted in Best Practices, CSS (including hacks), Web Development | 36 Comments