CSS, JavaScript and XHTML Explained

Quirks, random thoughts and funky finds discovered in day-to-day coding.

 

Javascript Switch Statement Quirks July 3, 2007

Filed under: JavaScript, Web Development — Estelle Weyl @ 10:21 am

Javascript: Things you should know

Note: This is part II of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. I try to cover quirks that are important, often lead to logic errors but don’t throw an error, and aren’t covered in most books or tutorials. The previous entry was Browser Detection versus Object Detection.

JavaScript switch statement:

There are three things you may or may not know about the switch statement:

  1. there is no datatype conversion ,
  2. once there is a match, all expressions will be executed until the next break or return statement is executed, and
  3. you can include multiple cases for a single block of code.

Data Type is important. JavaScript is NOT loosely typed when it comes to case comparisons

Javascipt is generally a loosely typed language. In other words, there is no need for data type declarations, you can easily change the data type, and you can compare values of different types. Normally in JavaScript data type does not matter. In regular if statement comparisons data type doesn’t matter unless you are using strict comparisons that specifically check for data type:

y = 5;
x = '5';
if(x == y){
  alert("they're the same"); // this alert will show
} 

if(x ===y){
alert("Data types match?"); //This will not show: different types
}

The exception is case values in the switch statement. For the case to be a match, the data types must match. Think for it as switch statements including === (strict equal) instead of == (equal) for case comparisons.

y = 5;
switch(y){
  case '5':
  alert("hi"); // this alert will not show since the data types don't match
}

In the above case, there is no match as 5 and ‘5′ are not the same datatype.

Break or Return statements are necessary

Although not required, if you omit the return or break statement in your case code block, once there is a match, all statements will be executed until the end of the switch statement or until the next break or return statement is encountered, whichever is first.

<script type="text/javascript">
//<![CDATA[
y = 5;
switch(y){
  case 5:
    alert("this matches");
  case 4:
    alert("this does not match, but will be displayed");
    break;
  case 3:
    alert("not shown due to break");
}
//]]>
</script>

In the above switch statement, there is a match in the first case, so the alert is correctly displayed. The script continues executing statements until it encounters the end of the switch statement, a break or a return, whichever comes first. Since there is no break, the second alert is erroneously displayed.

Multiple cases for a single block of code

<script type="text/javascript">
//<![CDATA[
y = 5;
switch(y){
  case 5:
  case 4:
  case 3:
    alert("this matches");
    break;
}
//]]>
</script>

If we extend what we just learned above — that once there is a match, every statement is executed until a break or return if found — then it makes sense that the alert in the above switch statement will be executed if any of the cases match.

 
 

hasLayout

Filed under: Browsers, CSS (including hacks), Web Development — Estelle Weyl @ 10:20 am

HasLayout:

HasLayout is a Microsoft proprietary property that determines how IE will render the dimensions of an element. It’s a boolean read-only value that is either true or false. When an element’s hasLayout property is false, IE has rendering quirks. The most common quirks include disappearing text in IE, and the most common solution is the holly hack. I prefer using float.

Properties that trigger hasLayout for IE:

  • display: inline-block; (even though IE won’t respect "inline-block" it will still trigger layout)
  • height: any valid value except "auto"
  • float: left or right (not none)
  • position: absolute
  • width: any valid value any value except "auto"
  • writing-mode: tb-rl
  • zoom: any valid value except "normal"

DOM for hasLayout:

  • el.style.hasLayout
  • el.currentStyle.hasLayout
  • el.runtimeStye.hasLayout

Other hasLayout notes:

  • body * { zoom:1 } would seem like a good idea, but elements with a zoom property set are a bit more expensive to render, so only add to necessary elements.
  • removing hasLayout: hasLayout is a read only property, so you can’t set it to false in JavaScript. To set hasLayout to false, set with with CSS such as setting position: static, set zoom: normal;, float: none; etc.
 
 

Browser Detection versus Object Detection July 2, 2007

Filed under: Browsers, JavaScript, Web Development — Estelle Weyl @ 11:52 pm

Javascript: Things you should know

Use object detection instead of browser detection

Note: This is part I of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. I try to cover quirks that are important but aren’t covered in text books. The next entry will be quirks with the javascript switch statement.

Use object detection instead of substring detection to determine browser support of your code. Browser detection involves using navigator.userAgent. There are several reasons why you shouldn’t use browser detection.

  1. Browsers lie about who they are.
  2. You may filter out browsers that support your code or fail to filter out browsers that don’t support your code..
  3. Browser detection isn’t future proof: can’t future proof your code against new browsers.

Instead, use object detection: test to see if your browser supports the object you want to manipulate. If the browser supports your objects, yay! You don’t need to know the name of the browser or version number, just whether or not it will support your code.

The most commonly used object detection to check to see if a browser supports the DOM is:

var supportsDOM = document.createElement && document.getElementsByTagName; 

This object detection does not mean you can use any object. It simply lets me know whether you should even try implementing your javascript in that particular browser. While the above is a good start, you should still do object detection before assuming browser support.

if(supportsDOM){
  var resolution = window.devicePixelRatio;
  alert(resolution);
}

At the time of this writing, the only browser that supports the devicePixelRatio property is Safari. See Targeting Safari 3.0 with CSS and Javascript. Safari will return "1", whereas all other browsers will return "undefined". Basically, just because a browser supports the DOM, it does not mean that it supports every object, property and method of the DOM equally, and that it doesn’t have it’s own propietary methods. Once you’ve determined that your browser supports the DOM, you still have to test for method and property support before using it.

if(obj.addEventListener) {
  //standards code
}
else if(obj.attachEvent) {
  //proprietary code
} 

A prime example is IE’s failure to support the WC3 standard addEventListener. Microsoft has it’s own event handling model, supporting attachEvent instead. When performing bject detection, always test for standards compliant methods before proprietary support. IE7 does not support addEventListener. IE8, or whatever the next version is, may support addEventListener and will continue to support attachEvent for backwards compatibility reasons. When IE finally supports the WC3 standard, putting your object detection in this order will ensure that browsers that support standards, whether or not they also support proprietary methods, will use the standard.

Exceptions to the use oject detection not browser detection rule

If you are still supporting IE 5.2 for the Mac, you may want to use browser detection to exclude it. Mac IE 5.2 returns true for if(document.createElement && document.getElementsByTagName), but crashes when it encounters advanced scripts. See Mac IE Hacks.

If you are actually trying to determine which browser is using for some non-javascript reason, such as maintaining statistics on visitors, then it makes sense to use browser detection.

Note: Apple has a good article on object detection versus browser detection.

 
 

Introduction to Firebug June 28, 2007

Filed under: Browsers, JavaScript, Web Development, firebug — Estelle Weyl @ 9:58 am

A Firebug Tutorial

This is an overview of the plugin, not a detailed explanation of all of it’s amazing features. This should be enough to get you started.

Installing Firebug

Firebug works with Firefox. There is a product called Firebug lite which you can include in a file via a javascript call in your file, for use in non-Firefox browsers, but I am not covering Firebug lite in this tutorial/overview.

To install Firebug visit the Firebug download page. Click on the huge orange button half-way down the page on the right hand side. You can also download it from Mozilla’s FireFox Add-ons site. Install it. Restart FireFox, and you’re good to go.

If you’ve already installed it, get the latest version! To update your extension, in Firefox select Tools > Add-ons. Then click on the button in the left hand bottom corner that reads "Find Updates".

Opening and Closing Firebug

Keyboard and Mouse Shortcuts for Firebug can be found at the Firebug Website. The three sets I use most often include:

  • Open Firebug: F12 or clicking on the green check mark at the right of the right of the browser status bar.
  • Close Firebug: 12 or clicking on the green check mark at the right of the right of the browser status bar or clicking on the red x in the upper right hand corner of the firebug window.
  • Undock Firebug into its own window: click on the red up arrow in the top right corner of the firebug window or Ctrl+F12 / ⌘+F12.

Firebug settings

  • Set Firebug to always undock in a separate window: open the firebug console. right click on the firebug in the upper left, select "options", then select "Always Open in New Window"
  • Increase/Decrease font size: open the firebug console. right click on the firebug in the upper left, select "Text Size". The font changes are really slight, but it does work.
  • Set Firebug to only work for specified sites: Start by disabling Firebug by right clicking on the green check mark and selecting "disable Firebug". Then right click on the greyed out icon and add the domains you want to enable Firebug on.

Firebug Window Overview

  • Console Tab: Contains command line javascript, shows javascript error message log, can enter JavaSript commands after the >>> at the bottom
  • HTML Tab: Shows HTML as an indented hierachy of DOM nodes, which you can open and close to see or hide child nodes.
  • CSS Tab: CSS inspector, view all loaded style sheets, modify styles on the fly. See list of styles sheets and select one to view from this pane by clicking on the drop down list on the top of Firebug window, to the right of "Edit".
  • Script Tab: Shows the javascript files and the calling document. See list of included JavaScript files and select one to view from this pane by clicking on the drop down list on the top of Firebug window, to the right of "Inspect". Set breakpoints and conditions underwhich break points appear.
  • DOM Tab: Shows all the page objects and properties of the window. As variables are properties of the window object, Firebug displays all JavaScript variables and their values.
  • Net Tab: Shows all the downloads, how long each resource took to download, the HTTP request headers and server response sent for each resource. The XHR tab is useful for AJAX debugging.

Edit your document on-the-fly.

You can change text nodes by selecting the text node with the "inspect" function and then clicking on the text node in the HTML panel.

Firebug is both an inspector and an editor. All objects in the HTML, CSS and JavaScript files can be edited with a single or double click. As you type, the changes are immediately applied in the browser window providing instant feedback. The DOM inspector allows for full in-place editing of your document structure, not just text nodes. Simply click on the "edit" tab next to the "inspect tab", and the left panel becomes a black and white text editor. In the CSS panel, Firebug autocompletes as you type. In the DOM inspector, Firebug autocompletes property names when you hit the Tab key.

Inspecting and troubleshooting CSS using Firebug

DOM inspector’s CSS tab reveals all applicable CSS rules for elements, including properties inherited from ancestor elements, lets you toggle on/off and edit individual style declarations and add new CSS rules.

Firebug hides rules that Firefox ignores: For example, Firebug will hide hacks targeting other browsers and CSS3 selectors that it doesn’t support. So, it will both hide intentional CSS filters, such as _height:25px; (the underscore is an IE6 hack) and p:first-of-type {color: #ff0000;} (a CSS3 :first-of-type pseudo-class selector currently supported only by Safari 3). This means, however, that if the reason your page isn’t looking the way you anticipated is because of a typo, you will need to use the developer toolbar to show all CSS and find your error.

Firebug shows all selectors impacting the selected element: When you inspect an element or node, Firebug displays the entire cascade of all the CSS attributes impacting that element, including attributes that were overwritten in the cascade. The right panel displays the selectors and attributes impacting the element in order of the cascade.

Firebug allows you to turn off styles impacting an element within the CSS: When you turn off an attribute, if that attribute value was overriding a different value in the cascade, the formerly crossed out value will become active so you can test what the page would look like if the attribute value were removed. To "turn off" an attribute, click to the left of the attribute in the right hand panel. A red "do not" icon do not will appear, and the attribute will be grayed out or disappear, and the strike-through of the new attribute value effecting the element from the cascade will be removed. You can toggle the attribute value back on by clicking on the do not. However, if the attribute has "disappeared" since it’s been overwritten, you have to re-inspect the element to see the missing attribute and toggle it back on.

Firebug allows you to edit attributes and attribute values: To change an attribute or the value of an attribute, click on the term or value, and edit it. Pretty simple! The effect of the change will be immediately visible in the browser window.

One of the best components of this feature is figuring out exact positioning, padding and margins. Firebug provides wonderful support for changing numeric values. Simply click on the numeric value you want to change and change it with the numbers on your keyboard, or click on the up or down arrow to increment or decrement the value by one.

Firebug allows you to add new attribute / value pairs to existing selectors: To add an attribute to a selector, double click on the selector. An input box with intelli-sense will appear. Hitting tab will bring you to a value text input box.

Firebug allows you to easily inspect ancestor elements: To the right of the keyterm "inspect", Firebug displays all the ancestors of the currently selected element. To inspect an ancestor, simply click on it in the list. The left and right panels will both change to display the properties of the newly selected element.

The Box Model: Evaluating Height, Width, Padding, Border and Margin

When you inspect an element, the left panel displays the HTML, and the right panel shows the CSS. Next to the CSS label at the top of the right panel is a tab labeled "Layout". This Layout tab illustrates the CSS box model as it applies to the selected element. To view the height or width of any other element on the page, simply select "inspect" while this window is open and hover your mouse over the inline or block level element you wish to inspect.

Evaluating download speed

The Net tab graphs the request times for all http requests that make up a page. Network monitoring must be turned on for the Net Tab to work, but it’s on by default (the options drop down on the right hand side of the firebug panel allows you to toggle this feature off and on). This is a handy way to test (and prove) that putting your javascript files at the bottom of your files, especially for javascript heavy pages, improves perceived download time. Total download time will be the same, but since browsers stop loading pages when they hit scripts until the scripts have been downloaded, the page will appear to download faster, which is a better user experience (see list item 5).

By left clicking on the plus sign to the left of the file name, Firebug displays the HTTP headers of each file that was downloaded.

In the 1.0..5 version of Firebug you can see how long it takes for HTML files only to be downloaded, CSS files only, images only, etc., or all files. YSlow, Yahoo!s performance tool, should be available as a plug in for Firefox by the end of the summer. In the meantime, Firebug’s Net tab is the next best thing.

JavaScript

The DOM inspector provides information about all the properties of all the objects in your document. The coolest feature of Firebug is that while making dynamic updates to your page will not alter the content visible in the "view source" feature of the browser, it will update the content in the Firebug panels. So, dynamically created content is visible not only in the browser (as it should be), but the generated code is inspectible (is that a word?) in Firebug.

The JavaScript profiler reports on the execution times of your JavaScript functions, so you can pin down performance JavaScript components that are slowing down your pages or javascript applications. To view the profiler, the submenu should be on "console", and click on "Profile" in the top menu (the order of the tabs is "Inspect |Clear | Profile"). Firebug lists all the functions that were called and the time spent for each function call. You can target what function you want Firebug to profile by adding console.profile([title]) to the start of the section your want profiled, and console.profileEnd() at the end.

The command line at the bottom of the console tab, which starts with ">>>" accepts commands in JavaScript. The results or your javascript command, if there are any, are then displayed in the console. There is a Firebug Command Line API that is worth taking a look at.

AJAX

As mentioned above, Firebug captures dynamic content and other DOM changes made to your webpage. If you take as an example the sample file created in my tutorial Beginning AJAX using the YUI Library, if you check the view source after calling the function (click on the link) via the browser’s functionality, you’ll only get the link that calls the AJAX function. If you view the source via Firebug, Firebug reflects changes made to the DOM, and includes the "Hello World" content. This is one of the core strengths of Firebug: without Firebug, AJAX requests and responses are invisible. With it, you can view the sent and received text as well as the headers that went along with it. You can also monitor how long it took for each request/response with the Net tab.

You can see XHR response by clicking on the Net tab, and then the XHR tab in the sub navigation that opens up when you are in the Net view. While the All Net tab is like yslow, the XHR focuses on the AJAX only. If you click on the plus sign to the left of the response file, you can see both the headers and the content of the response.

Details of the Net tab’s XHR sub-tab

When a request is made to the server via a XMLHttpRequest object, Firebug logs the POST or GET request, the response headers and the raw text of the response. To view this data, click on the Net Tab’s XHR sub-tab. This will show a list of the calls and the time it took for the response. To the left of the request click on the + or simply click on the request (it is a link). Three tabs will appear in the case of a GET request, four for a POST:

  • Params: Displays the name/value pairs of the request URL
  • Headers: Displays requestion and response headers
  • Response: Shows the actual data received from the server as it was received.
  • Post. Displays the data sent to the server from a POST request (tab only shows for POST requests, not GET requests).

These four tabs are useful in development and debugging. Check the POST and Params tabs to ensure your request are being correctly posted. Check the Response to determine the format of the response and ensure that your JavaScripts are written to handle that formatting. If you don’t control the feed that you are fetching, you can copy and paste the response into a text editor, format it so it’s human legible, and work that way.

Debugging AJAX and other JavaScripts

To debug AJAX, it’s similar to how you debug JavaScript above, except for the console.log is even more helpful, since you are reloading components of the page and not the whole page (reloading the whole page resets the HTML, JS and CSS to what is defined in the static files). Firebug provides the console object that has several methods usable for logging. Properties of console object include console.debug, console.info, console.warning, and console.error. When one of these methods produces an output, Firebug links to the line causing the output so you can quickly find the responsible code.

One of the other ways to debug is to set breakpoints (yay! no more alerts!).  The "Script" tab allows you to pause execution on any line. Clicking on the line number in the script tab sets a breakpoint.  You can make that breakpoint conditional by setting a statement that if true will trigger the breakpoint.  Simply right click to the left of the line number to set an expression (where you had left clicked to set the breakpoint) or right click on the line and select "Edit breakpoint condition": "this breakpoint will stop only if this expression is true" is the message you should see. You can contine, step over, step into or step out of a line. The right panel has a "watch" tab where you can inspect the value of local variables (click on objects to view their properties). Hovering over an object in the script activates a tooltip that displays the object’s properties.

Problems with Firebug

Webpages never finish loading: likely because there is a javascript error in the page, and Firebug has put a breakpoint at the error and halted the script.

Firebug crashes my Firefox some of the heavier Web 2.0 sites that I visit, like Netflix and Yahoo! Mail. Firebug keeps track of all the errors. This can use up a lot of memory and crash the browser. Also, likely irrelevant, but SoThink SWF makes Firebug crash FF.

Solutions:

Disable Firebug for a particular domain: Unless you develop for a site that crashes your browser, you can simply turn off Firebug for a domain/subdomain.. To turn off Firebug, right click on the green check mark (or red x if there are errors) in the status bar and select "disable firebug for thisserversname.com".

Disable Network Monitoring: Sometimes disabling Firebug for a particular domain is not an option . For example, I code a small part of a much larger internet application which throws errors and therefore never finishes loading, but disabling Firebug is not an option since I am working on that page.. To resolve this issue, click on the Net tab. When on that tab, to the far right you will see "options". Select "Disable Network Monitoring". Since I have selected that, I no longer crash my Firefox, and can work on the website I need to work on. (I did update my Firebug, and that might have helped the issue too. Not sure.)

Update Your Version of Firebug: Firebug is continuously being updated and bugs are being fixed. To update to the latest version of Firebug, in your FF browser window select Tools > Add-Ons > Find Updates, and FF will check for and install upon request, the most recent release of Firebug and all of your other FF extensions.

Notes:

  • Firebug 1.05 and earlier do not work with Firefox 3.0, currently in beta
  • Joe Hewitt developed Firebug and offers it for free. Consider giving him some love in the form of money.
  • For more in depth view, view Joe Hewitt: Welcome to Firebug which I included below. The above tutorial is more of what you definitely need to know. The video covers the more advanced features. Take a look at it if my overview doesn’t provide enough info, especially in the area of JS debugging and XHR debugging.
 
 

Targeting Safari 3 with CSS and JavaScript: Safari3 Hacks & Filters June 22, 2007

Filed under: Browsers, CSS (including hacks), Web Development — Estelle Weyl @ 1:14 pm

See also Safari 3.0 CSS3 Support
Google Chrome and Safari 3.1 CSS3 Support and
CSS Hack/Filter for Google Chrome and Safari 3.1

CSS Filter: Safari CSS Hack

Not that Safari 3.0 on Windows is a grade-A browser yet, and not that I have figured out any reasons to need to hack for this browser yet, but two good potential CSS filters include using :first-of-type and -webkit-min-device-pixel-ratio.

:first-of-type

Safari is the only browser that seems to understand the :first-of-type pseudo class. Safari fails only in that if you add a siblingnode of the same type with javascript prior to the first of the type, safari will target both of the elements instead of just the new one. That failure shouldn’t be a concern in 99.999% of the cases.

To target Safari, simply code:

body:first-of-type p {color:#ff0000;}

Notes

  • :first-of-type is a CSS3 selector, and as such, other browsers will eventually start supporting it, and will therefore be targeted by this filter. In other words, while this is a simple method to target Safari 3.0 to the exclusion of all other current browsers, it is not future proof.

-webkit-min-device-pixel-ratio

Safari added the feature, device-pixel-ratio, that determines how a CSS pixel relates to a device pixel. This CSS3 media query allows for the inclusion of a separate CSS file:

<link rel="stylesheet" media="screen and min-device-pixel-ratio: 0" href="safari3.css"/>

This "if" statement includeing min-device-pixel-ratio will return "true" for Opera 9, Firefox 2.0 and Safari 3, so while it’s a good solution for omitting IE, it won’t work for targeting Safari 3.0 only.

@media screen and (-webkit-min-device-pixel-ratio:0){
                p {color: #00ff00;}
}

The above syntax is more browser specific, and targets both Safari 3.0 and Opera 9. The benefit of this filter/hack over the :first-of-type pseudoclass is that since CSS3 is supposed to support device-aspect-ratio and possibly device-pixel-ratio the -webkit portion of the syntax will likely not be supported by additional browsers in the future. In other words, it seems like a more future-proof solution than the :first-of-type, even though :first-of-type is a more browser specific solution at the moment.

Notes:

  • Webkit is basically the "opensource" framework that is the basis for the Safari browser, so -webkit is not standard.
  • For more on Safari and DPI visit Webkit’s High DPI Web Sites blog entry.
  • In the Opera CSS support list ,device-aspect-ratio and min-device-aspect-ratio are listed as supported. Although not listed, Opera supports media query device-pixel-ratio when tested.

Targeting Safari 3 with JavaScript

Safari is the only browser that supports the window property devicePixelRatio. So, similar to that old fashioned document.all, you can browser sniff this way:

<script type="text/javascript">
   isSafari3 = false;
   if(window.devicePixelRatio) isSafari3 = true;
</script>

Hedger Wang provides a sample in his blog.

Notes:

 
 

Making the Web Accessible June 16, 2007

Filed under: Accessibility, Best Practices, Web Development — Estelle Weyl @ 7:19 pm

Web Accessibility / Section 508 Guidelines

Making your site accessible

Web accessibility is the ability of users with various functional requirements to use web sites easily and effectively. This includes keyboard access, screen enlargement, screen reading and voice recognition. If you don’t think this is important, just remember that your two most important visitors are blind, deaf and unable to use a mouse: googlebot and slurp, Google and Yahoo!’s spiders, can only read the text of and tab thru your page. They can’t see your cool mouseover effects, interpret the nuances of your images, or enjoy your nifty sound effects.

Below are brief rules to make your site accessible. After the table of contents below are methods to ensure that your content is visible to users, but to considered compliant that content must be presented in an accessible manner. The list below should get you 90% of the way there. The rest addresses specifics to ensure complete access.

Here are the brief rules:

  • Content that is well written will be easier for everyone to access including people with cognitive and learning difficulties. Content should be short, simple and well organized. Paragraphs should be brief with one key idea per paragraph. Make sure there are no spelling or grammatical mistakes.
  • The language of the content should be defined using the "lang" attribute. In addition to defining the language for the document, all changes in the primary language of the page should be indicated. Provide definitions/explanations of technical terms, abbreviations and acronyms.
  • Each page must have a unique title element, which relates to its content. Use meaningful headings and subheadings. Page headings and sub-headings should be defined using <h1> to <h6> heading structure. Correct mark-up should be used for lists. Sub-lists should be nested properly. Content should appear in paragraphs or list items: avoid anonymous (tag-less) text.
  • Users must be able to reach and trigger all links, forms and functionality without the use of a mouse. Additionally, the text of links and the "alt" attributes of image links should make sense when read out of context.
  • Start with accessible content by first coding your page in XHTML first, with no presentation (CSS) or interactivity (Javascript). Then add the presentation (CSS) and behavioral (JavaScript) layers with external stylesheets and scripts. Think "Web Standards": if your site is semantically coded, it will likely be accessible.
  • Do not target assistive technology with display: none, as that will hide the content from all users with CSS enabled, including screen readers. Instead position the hidden content off the page. Do this wisely as form elements and links positioned off the page can still receive “focus” by use of the keyboard.

Assistive Technology

Screen readers are a form of assistive technology.  A screen reader is software that sits on top of other applications, reading aloud what other sofware displays to the screen. While web developers often think of screen readers when developing accessible website, we need to remember that screen readers are not the only assistive technologies that may be used with your site: users can magnify your site, use the browser to increase font size, visit your site with refreshable braille display devices or print your pages with braille printer, navigate your site with a keyboard or apply their own style sheet to your site.

Section 508 guidelines and other tips to making your site accessible

The WCAG (Web Content Accessibility Guidelines 1.0) recommendations were written in 1999, so are a bit outdated. The following is based on their recommendations and updated to reflect modern web standards and Web 2.0. The WCAG 2 guidelines are still in draft form, but are nearing completion. You should find this page more helpful and easier to understand than the official guidelines.

Below are guidelines to consider when developing websites. While the W3C calls these "guidelines", they should be considered "rules". Following these guidelines will not only help make your website more accessible to those with disabilities of various sorts, but your site’s search-ability will improve, your site will likely function on alternative media such as cell phones, you’ll be considered a really good person and you’re site will be legal in all the countries that require sites to be accessible.

Text Equivalent for images and animations:

A text equivalent for every non-text element should be provided (e.g., via "alt", "longdesc", or in element content).

alt attribute: alternative text for images

The "alt" text attribute provides a title or descriptive phrase about the image it accompanies. The "alt" attribute should describe the content of the image. Describe the image, but don’t start with "This is an image of…". The user already knows it’s an image. If you don’t know what alt text to use, imagine reading the document over the phone: how would you describe the image to the person on the other end? Alt attributes are essential for users of reader software who are vision impaired, it is valuable for users of graphical browsers who have "load images" turned off (which many cell phone users do), and it helps you should your image fail to load. It is also useful for users of text-only WWW tools like Lynx and some cell phone browsers. While some images formats, such as PNGs, allow for the inclusion of meta data describing the content, no browser or reader supports this function, so while you may include the data for future comatibiltiy, you can not rely on it for current compatibility. If I haven’t convinced you of the importance yet, it also helps with SEO, since search engines have no way to "read" your images.

There are 2 circumstances in which null or empty alt attributes (alt=””) may be used: layout images and images that are included within the same anchor tag as a textual link. If you are a web standards oriented web developer then you likely will never have empty alt attributes. Why? Because good web developers use background images, not layout image. And good web developers use background images (and sprites) instead of link foreground images.

longdesc attribute: long description for images and media

The "longdesc" attribute can be essential when an image conveys important information such as a pie chart or a scientific discovery. The longdesc is a link to a separate text only page containing a longer, text only, description of the the image. If the contents of the image are described within the text content of the page, a longdesc is not necessary.

Multimedia:

Equivalent alternatives for any multimedia presentation should be synchronized with the presentation. In English, when including multi-media components in your web page, such as a flash movie, an animated gif, a video clip, etc., the alternative text describing the contents of the media should change as the presentation changes. Any dynamic changes occuring in the multimedia content (either in a <frame>, <img>, <object>, or <script>) must also update the "alt" element when it changes.

Implementation of this web accessibility requirement include captioning and transcriptions of any spoken audio in the media (think "hearing impaired"), and text descriptions of the visual changes (think "visually impaired"). You do not need to include captioning for non-informative sounds, such as background music. But include captioning for all sounds that convey meaning in the audio, including all spoken words and background sounds, such as a window breaking, and even words to a song, if the sound or song lyrics are necessary in conveying the meaning of the multimedia component.

Color:

Don’t convey information with color only

Web pages should be designed so that all information conveyed with color is also available without color. For example, my chart of browser CSS support uses color to show various levels of browser support. Without color this chart would be completely useless were it not for the semantic markup of checkmarks, deltas and exes providing reduntant data. Visual color cues should not be the only way of conveying information, as had I only used color in this chart, not only would this page be a challenge for color blind users, but users accessing this page via cellphones, Lynx, with CSS turned off, and with Safari (there is a typo in the page that i have yet to fix, so the colors don’t show in Safari) would be completely unable to use this chart.

Use enough contrast in your web design so your site is readable for users with color blindness.

In developing your web pages, choose text and background colors to provide maximum contrast. Page design must present a clear contrast between foreground and background colors. Many people think that color blindness means that sufferers see the world like a black and white TV. This form of colorblindness does exist, but is extremely rare. Color blindness, though, is not rare. Thirty percent of all males suffer from some form of color deficiency rendering colors as grays or spreading one color across several others.Contrast is also very important for individuals who can see but have reduced vision. Is your text green and are your links of a similar hue with no text decoration? Take a look at your website as with simulated color blindness.

In developing the site, do not include any HTML color on the page. All the colors should be controlled via external style sheets. This allows the user to implement their own style sheets and color palette.

Style Sheets:

Documents should be coded semantically, included coding the text in an order that makes sense if it is read without a style sheet. Headers should be used for headers, lists for lists, paragraphs for paragraphs. This helps not only for humann accessibility, but enables your pages to be accessible to search engines. Separate your presentation, or "style", from your content. All your style sheets should be external. Do not include inline styles. Do not use !important.

All text should re-size relative to browser font size settings: use ems instead of pixels in declaring font-size. If you declare font size using pixels, IE6 will not change the font size when the user chooses to change it via their browser. IE6 does respect relative font sizes, which is why ems are recommended instead of pixels. Percentages work as well, but they are a wild beast to tame when it comes to the cascade and cross browser issues; so use ems. (WCAG 3.4: Use relative rather than absolute units in markup language attribute values and style sheet property values. Priority 2)

Language:

Natural Language

Indicate the language of your content. If the page is in English, French, Spanish or Urdu, you need to let the browser know. The screen reader uses this information. Google uses this information. If you then use a different language within the page, indicate that the language has changed for that section of the page. (WCAG 4.1 - Clearly identify changes in the natural language of a document’s text and any text equivalents (e.g., captions). [Priority 1]) In print, foreign language quotes are usually displayed in italics. Similarly, you should use the lang attribute to indicate language.

<p>I had another <span lang="fr">deja vu</span> last night.</p>

Using the lang attribute you are informing the screen reader to use alternative pronunciation, informing braille translators to not contract letters, and allowing the Babel Fish translator how to interpret individual chunks of content.

Language Level

Use the clearest and simplest language appropriate for a site’s content. If you are writing a children’s site, use first, second or third grade level language as appropriate. If you are writing for the general public, use the simplest language that isn’t pedantic. Generally, the eigth grade level is appropriate. If you are writing a scientific journal article, or a technical article, use appropriate terminologogy without being needlessly complex.

Try to remember what you learned in your middle school English classes: describe what you are going to talk about in headings, and state your subject or theses of your paragraph at the beginning of the paragraph or section, and limit your paragraphs to one main idea.

Abbreviations and Acronyms

Specify what each abbreviation or acronym in a document means. Although the WCAG recommendations state that you should expand the term only where the first abbreviation or acronym occurs, your visitor may be visiting your page thru an anchored hyperlink, thereby missing the defintion. You don’t have to expand all abbreviations or acronyms: expand ones that could be helpful to the user, and don’t expand ones that are used in everyday language. For example, we all know the definitions is for TV, DVD is it’s own definition and who knows what it really expands to. If you’re going to use THC you need to expand it because you’re likely defining it, and few people remember that it means Tetrahydrocannabinol. You will want to define it the first time you use it for all users, and use <acronym title="Tetrahydrocannabinol">THC</acronym> for all other occurrences within a page. If you are going to use an acronym that is commonly used and not easily misconstrued, such as HTML, expand it the first time it’s used: if a user doesn’t know what it means, they can look for the first occurrence.

Server-side image maps:

Likely not an issues for most developers, and server-side image maps have become almost obsolete. Most sites have moved away from server-side image maps. The exception is for such things as geographical information system clickable maps. So, if you insist on a server side image map, redundant text links should be provided for each active region.

Client-side image maps:

Include the alt attribute for each map area. Also include the alt attribute (duh!) in the image. Client-side image maps, unlike server side image maps, are generally accessible with just a little code, so the recommendation is to include client side image maps instead of server-side images maps. Modern browsers support client-side image maps, with the addition of "alt" attributes for the image hot spots, assistive technology readers can provide additional clues. However, if the user has "load images" turned off, the only approach is to provide alternative links. So, include an "alt" attribute in each and every hot spot.

Data tables

Tables should only be used for tabular data. Don’t use tables for layout. Again. Don’t use tables for layout.

Row and column headers should be identified for data tables.

Using row and column headers — <th> instead of <td> — becomes crucial when a table is larger than two columns or two rows. Without the headers, assistive technology such as reader software can only recite the table contents with no reference to what that column or row pertains to.

Multi-logic row or column headers

The <thead> and <tbody> tags should be used to differentiate between the data table header and the data table body. Markup should be used to associate data cells and header cells for data tables that have two or more logical levels of row or column headers. Additional information such as "summary" and "scope" can be applied to data tables to render their contents and intent meaningful to users of assistive technology. The "summary" attribute should summarize the data that the table contains. "Scope" can be very useful for column headers. For simple data tables, the “scope” attribute should be used to differentiate between row headers and column headers. For complex data tables, each data table cell should be explicitly associated with its relevant table header. To do this, add an “id” attribute to the <th> tags and reference this id by using the “headers” attribute within each <td> tag.

Frames

Don’t use frames, especially complex frame sets. But, if you are going to use frames, title frames with text that facilitates frame identification and navigation. If you do use frames (please don’t) include a “title” attribute that accurately identifying its role or purpose. With the "title", "name" and "longdesc" attributes, frames can be made more navigable for reader software, but they still shouldn’t be used. Iframes are o.k.  Use the title attribute for iframes.

Flicker Frequency

Unless you are aiming to be on http://www.websitesthatsuck.com, you shouldn’t have flickering on your website.  But, if that is indeed your goal, design pages to avoid causing the screen to flicker with a frequency greater than 2 Hz and lower than 55 Hz. Flicker and continuous motion (as from applets or scripts or from refreshes) can cause seizures in individuals with photosensitive epilepsy. Try not to use time-sequenced elements. If used, choose your timing carefully.

Text only equivalent

Provide a text-only page, with equivalent information or functionality to make web pages accessible when compliance cannot be accomplished in any other way. The content of the text-only page should be updated whenever the primary page changes. Only resort to alternative pages when there aren’t any other ways of making your pages accessible. An out-of-date page is as frustrating as one that is inaccessible since, in both cases, the information presented on the original page is unavailable. Before resorting to an alternative page, reconsider the design of the original page.

Making Scripting languages accessible

When pages use scripting languages to display content, or to create interface elements, the information provided by the script should be identified with functional text that can be read by assistive technology. The easiest method to provide this accessible alternative is to write HTML code which includes the <noscript> tag. Other options include ensuring that dynamic content and refreshes can be made or are accessible.  Some will argue that the <noscript> should not be used; and I definitely understand their rationale, since the <script> should be external making <noscript> moot.  However, there are certain cases where it does make sense, so I won’t say "don’t use it."

If you are using javascript and have a "return false" as an event for the onClick event handler, the link’s href should redirect to a page where the required effect. Do not use <a href="#" ....> or <a href="javascript:.....>. Instead use <a href="validURL....>. If you have an X as a link to hide a div on a page, clicking on the link to with javascript turned off should redirect the user to a page with that div hidden.

According the the W3C, you should use event handlers in pairs for mouse users and keyboards users: using "onmousedown" with "onkeydown", "onmouseup" with "onkeyup" and "onclick" with "onkeypress", but since most sites aren’t accessible, many users who are unable to use mice actually set up a key to act like a mouseclick, and using onkeypress can override their settings. So, it’s important to make sure that any event that is required via javascript is also available to those without javascript.

Accessible AJAX

Screen readers are not informed when an AJAX or DHTML implementation dynamically changes the content of the page. AJAX is considered accessible if it doesn’t change the content of the page to any extent other than enhancement, or, if it does change the content of the page, that the user is informed of a change by a means other than a visual cue. When content is dynamically changed, the new content should receive focus to inform the user that the content is new. However, only form elements and links can receive focus.

There are two suggestions for making AJAX more accessible

The suggestion first is to make the screen reader know there new content by giving a tabindex value of -1 to the new elements unable to receive focus. Although -1 is not a valid tabindex value, it is able to receive focus with JavaScript, but will not be placed in the tab order, which makes it findable to screen readers but will not cause problems for keyboard navigators. To make dynamic content available, give focus to added content via the tabindex using javascript.

The second suggestion is to use the role attribute. Not just in with AJAX, but with everything in Web 2.0 applications, anything can be a button or a control interface (like a slider or container). The accessibility problem is that there’s no way for a screen reader to know about the functionality of those elements. The XHTML role attribute enables the addition of semantic information to the containing element.

Applets, Objects, Plug-ins

When a web page requires that an applet, plug-in or other application be present on the client system to interpret page content, the page should provide a link to a plug-in or applet that complies. Objects and data which require plug-in applications can be presented in HTML code in a nested manner such that, if the user’s browser can’t display the topmost data type, it will attempt to display equivalent data type in the object specification. This is more complicated HTML code to create and requires several data types to be resident on the server, but it is a more complete method of inclusion which favors neither advanced nor dated browser technology.

Forms

When electronic forms are designed to be completed on-line, the form should allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues. If you are going to dynamically submit the form based on user action other than clicking on a submit, ensure that the form is still submittable with javascript disabled.

Also, every form field should have a label element that is uniquely associated with it using the “for” and “id” attributes. Where a textual label does not fit into the visual design of the page, the field should still have the label hidden through CSS. Remember that you should not use display: none, as that will hide it from screen readers as well.

Content tracking

A method should be provided that permits users to skip repetitive navigation tasks. There are a number of methods of facilitating navigation for users of assistive technology. Be consistent in page-to-page design, designers can provide a jump-link to bypass a series of links on a page similar to the "back to top" used in long pages, when using multiple links close together, separate the links so the reader software can parse it correctly. For example, use list items or separate text links with a pipe (|). Links should be referenced with text which make sense if a user if link-jumping. Also, consider adding a site map, which is useful to nearly everyone.

Links need to be contextual and real

Contextual Links
Links need to mean something. Can you images tabbing thru a list of "MORE", "MORE", "MORE" with a screen reader. While your designers and marketing team might insist that your links look meaningless, you can still make meaningful links with XHTML and CSS.

The XHTML content will look like this:

<a href="link.html">MORE <span class="accessibilty"> on Contextual Links</span></a>

and the CSS looks like this:

a span.accessibility {
   position: absolute;
   left: -2000px;
   }

In this manner, visually it looks like just the word "MORE", but to the screen reader the purpose of the link is visible. Do not use visibility: hidden; display; none; as hiding from the screen also hides it from the screen reader

Real Links with Real Destinations

All <a href=" ... should link to a real URL or a real anchor.
If you have a link with an event handler that retrieves content via AJAX, the href of that link should redirect the user to a page that contains the content that would have been retrieved. If you don’t have a destination for the link, don’t use a link.  You can add event handlers to any object in the DOM, not just links.  The best way to understand this concept is to turn off javascript and make sure that all of your links are indeed links. If you are including an element simply to create a dynamic effect, consider employing a span with an event handler attached instead of a meaningless javascript:void().

Timed Response

When a timed response is required, the user should be alerted and given sufficient time to indicate more time is required.

Validation

The site should validate. You can validate your web page here.

The "Role" Attribute

In Web 2.0 applications, when an HTML element such as a form element is converted into a button or a control interface, there is no way for the screen reader to understand the conversion and the functionality of the converted element. The XHTML role attribute enables the addition of semantic information to converted elements.

<p class="note" role="note">
<ul role="navigation">

See the w3 guidelines and ARIA Roles for more information.

 
 

XHTML v. HTML, Strict v. Transitional June 4, 2007

Filed under: Best Practices, DTD, HTML, Web Development — Estelle Weyl @ 9:47 am

Comparing XHTML and HTML, Strict and Transitional

Note: Yes, this issue has been rehashed all over the web. I am addressing it because 1) you will be asked this at your next job interview, 2) very little has been written on Strict versus Transitional, and 3) it’s not easy to find info on what will make seemingly valid code not validate.

The difference between strict and transitional XHTML:

Transitional is a forgiving form of doctype.While you must code cleanly — properly nested lowercase tags — transitional allows deprecated elements and attributes to pass validation. The strict doctype is strict: deprecated elements and attributes will fail to validate under a strict doctype and may well display incorrectly as well.

For example, <p align="left"> and <center> will validate in transitional, but not in strict mode since the align attribute and the <center> element are both deprecated.

Similarities in HTML 4.01 strict and XHTML Strict

HTML 4.01 strict will also fail to validate if you include depreciated elements and attributes. HTML 4.01 will fail to validate if you include XML style closing syntax on empty elements.

Differences between HTML and XHTML

The primary benefit is that XHTML is more widely accepted in non "computer" devices like cell phone, palm devices and other scaled down browsers. This is commonly called portability between devices.
XHTML is also said to be extensible: new tags can be added. Also, XHTML, due to it’s stricter nature, forces the developer to write cleaner code (yes, that is a ver good thing).

Here are "official" differences between XHTML and HTML:

  • In XHTML the elementy tags must all be in lower case as must all the attribute names. In HTML you can code willy-nilly. Nothing in the W3C states that attribute values need to be lowercase, but some, like ID, are case sensitive.
    Note: Even if you have declared a HTML doctype, all lowercase, while not required, is recommended.
  • In XHTML all attribute values must be encased in single or double quotes. In HTML, only attribute values with spaces or special characters were required to be in quotes.
  • In XHTML, every opening tag must have a closing tag. Empty elements such as img and br must be self-closing. In HTML tags can be left unclosed. So, while this reduces the number of characters on a page, it also allows for sloppy code.
    Note: Self closing tags, such as <br />, will cause strict HTML to not validate.
  • In XHTML, all tags must be properly nested: If you start tag <a> and then start tag <strong>, you must close tag </strong> before you close the </a>
  • In XHTML, all attributes must be coded as attribute/value pairs. The default selected option in XHTML should be written selected="selecterd". In HTML, the same would simply be coded as selected.
  • In XHTML, the elements need to be coded in a semantic manner. Tables and forms can not be included in paragraphs, but form elements, being inline elements, need to be contained within a semantic block level element, such as a paragraph or table cell.

The most common errors

I’ll reiterate some points made above because this is what people always get wrong (and if you’re in a job interview, you’re more likely to impress if you know these):

  • HTML 4.01 will fail to validate if you include XML style closing syntax on empty elements.
  • Strict DTD’ed documents will FAIL if you include deprecated elements and attributes.
  • In XHTML, there are no "empty attributes." All attributes must be in the form of name/value pairs.
 
 

Web Developer Interview Questions May 27, 2007

Filed under: Web Development — Estelle Weyl @ 4:31 pm

Web Developer Interview Questions:

The main technologies required for a web developer are CSS, HTML and JavaScript. A good web developer also needs to have a grasp of and interest in both web standards and accessibility. While most web developer roles require other technologies such as Unix, Apache and server management, MySQL & PHP or SQL & ColdFusion or other dB and programming technologies, CVS, Perforce, or other source control management interfaces, I am only going to cover the technologies that span all Web Developer job descriptions: HTML, Web Standards and Accessibility, CSS and JavaScript.

The main skill I look for in a web developer is intelligence*, a desire to learn and an adoration of web standards. These questions target knowledge rather than capacity to learn. So, for each question remove 2 points if the answer, whether correct or not, sounded like it was quoted from a text book or this blog entry (unless, of course, you are interviewing me). Add points for interviewee efficient thought processes: if they didn’t know the answer to start with but figured it out in the end.

Please have a look at Web Developer Resume Screening for thought on how to filter through resumes to find good Web Developer applicants.

* Note: Intelligence ≠ Education. A Masters or PhD may just mean that they had the time and money to delay getting a job. Look for people who can think, not ones who regurgitate text books.

XHTML, CSS & JavaScript Web Developer Applicant Questions

XHTML Web Standards Interview Question

Question:

What is a DTD? What DTD do you generally use? Why? Pros and cons.

Answer

See the bottom half of DTD: the Document Type Declaration

Answer Rating:

  1. Completely wrong answer though pretends to know it
  2. I don’t know (I give points for honesty), trying unsuccessfully but honestly to give the right answer
  3. Knowledge of the definition, but doesn’t know why they are used.
  4. Knowledge of which one to use and why
  5. Explanation of Quirks mode versus Regular mode and analysis of which one is best for different media

Accessibility Interview Question

Question

Tell me some considerations in selecting font size?

Answer

Font sizes should be declared using relative measurement values, such as ems, via a style sheet, without the use of the term !important. There are issues with browser font size enlarging which can be rectified via CSS.

Answer Rating

  1. uses <font> tag
  2. Gives an answer using pixels using CSS
  3. Explains that font size should be declared using relative font sizes
  4. Explains that font size should be declared using ems or percentages
  5. Gives the answer above

CSS Interview Question

Question

a) What are the possible values for the display attribute that are supported by all browsers?
b) What is the default value for the display attribute for the image element? (what is the difference between inline and block level elements)
c)What does display: run-in do?
d) Difference between "visibility:hidden" and "display:none"? What are the pros and cons of using display:none?

Answer

main values: none, block, inline, list-item, run-in
all values: inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none | inherit
default value: inline, block or list-item, depending on the element. The <img> is an inline element.
Run-in should make the run-in element be the first line of the next sibling block level element, if it is before a block level element that is not floated or absolutely positioned. If the next sibling is positioned or floated, then the run-in element will be a block level element instead of appearing in-line.
PPK’s Quirksmode explains it well. The w3schools lists table display values.
When visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page.  If the display is set to none, the element does not occupy any space on the page — as if it didn’t exist..

Answer Rating

  1. Doesn’t know
  2. Knows the answer to A
  3. Knows the answer to A and D
  4. Knows the answer to A, B and D
  5. Knows the answer to C too!

CSS Interview Question

Question

a) What are the five possible values for "position"?
b) What is the default/initial value for "position"?
c) How does the browser determine where to place positioned elements
d) What are the pros and cons of using absolute positioning?
e) if they are really advanced, ask about IE z-index issues with positioned elements.

Answer

a) Values for position: static, relative, absolute, fixed, inherit
b) Static
c) They are placed relative to the next parent element that has absolute or relative value declared
d) Absolutely positioned elements are removed from the document flow. The positioned element does not flow around the content of other elements, nor does their content flow around the positioned element. An absolutely positioned element may overlap other elements, or be overlapped by them.
e) IE treats a position like a z-index reset, so you have to declare position of static on the parent element containing the z-indexed elements to have them responsd to z-index correctly.

Answer Rating

  1. Doesn’t know
  2. Knows 4 out of 5 answers in part A
  3. Knows A & B
  4. Knows A, B & C
  5. Knows A-D
  6. Knows E too

CSS Interview Question

Question:

Write a snippet of CSS that will display a paragraph in blue in older browsers, red in newer browsers, green in IE6 and black in IE7

Possible Answer:

#content p{color:blue}
html>body #content p {color:red}
* html #content p{color:green}
html>body #content p {*color:black;}

Answer Rating

  1. Doesn’t know
  2. Knows how to declare one color, but no hacks
  3. knows the html>body hack and * html hack
  4. Knows all the hacks, but doesn’t validate or uses conditional comments in the HTML
  5. Gives you the right answer and explains why the CSS won’t validate, or, uses a valid hack, other than conditional IE comments, instead of the above answer.

Basic Javascript Interview Question

Question:

What is the correct way to include JavaScript into your HTML?

Answer:

See Including Javascript in XHTML for answers.

Answer Rating:

  1. <a href="javscript:function()"> - and other incorrect answers
  2. verbally explains the theory but doesn’t know how to do it
  3. correct explanation using inline event handlers or inline code
  4. discusses and knows how to implement javascript event listeners
  5. Explainst how you include JS within an XHTML document and ensure it validates using CDATA, explains

Basic Javascript Array / XHTML Form Interview Question

Question

Are the following all equal, and, if so, what would your code look like to make the following all equal the same thing:

  alert(document.forms["myform"].elements["field"].value);
  alert(document.forms[1].elements[1].value);
  alert(document.myform.field.value);

answer:

<form name="myform" method="post" action="something">
<input name="anything" value="anything" type="something" />
<input name="field" value="something" type="something" />
</form>

Answer includes knowing that the form is the second form on the page, and that the field input element is the second element within that form.

Answer Rating

  1. Doesn’t know how to code forms and doesn’t know that the first index of an array is 0.
  2. Knows either how to code forms with valid XHTML or that array starts at 0, but not both.
  3. Knows how to code forms but not correctly, but omits something like doesn’t know that the form needs to be the second one on the page, and the element is the second one in the form. Would know how to do it if they actually put thought into it.
  4. Codes the form correctly, but uses ID instead of name
  5. Codes everything correctly

JavaScript Interview Question

Question:

How do you dynamically add a div with stylized content to a page?

Possible Answer:

newParagraph = document.createElement('p');
newParagraph.setAttribute('class', 'myClass');
newText = document.createTextNode('this is a new paragraph');
newParagraph.appendChild(newText);
myLocation = document.getElementById('parent_of_new_paragraph);
myLocation.appendChild(newParagraph);

Answer Rating:

  1. Wrong Answer (i.e. "you can’t"), I don’t know.
  2. Use JavaScript, with no knowledge or incomplete knowledge of how that is done. Suggesting innerHTML, but not really knowing. Or explanation of accessibilty issues surrounding this.
  3. Able to explain how you create a node, add content to the node, add a class attributes to that element, and then add that node as a child of the parent element (the above example)
  4. Explanation of how to do it (worth 3 points) and explanation as to issues that arise when doing it, such as screen readers not knowing that text has changed, IE6 and IE7 not applying styles included with added content, not duplicating IDs, etc.
  5. Has no clue how to do it to start, but can figure it out with guidance: extra points for the quick learner!

Other questions ideas:

Q: How do you organize your CSS? How do you come up with id and class names (what naming conventions do you use)?
A: While there are no right answers, there are best practices. Issues to look for are not having div mania, no inline CSS, no presentational markup, minimal use of classes, understanding the CSS cascade.

Q: What do you think of hacks? When should you use them? If you use them, how do you maintain them? What can be done to avoid needing to use box-model hacks? (if they aren’t pros, you can ask them what is the issue with x-browsers and the box model)

Q: What are the pros and cons of using tables for layout? Do you use tables? What are the pros and cons of tableless design? How do you generally layout your pages?
A: check for them NOT using tables

Q: Check to ensure that they separate structure and semantics first from presentation later? Do not ask about this during HTML, but do in webstandards.

Q: What are some deprecated elements and attributes that you use, and in what instances do you use them?
A: List of deprecated elements and attributes.

Q: What is involved in making a website accessible? What are arguments you use to convince others to invest in making their web site accessible.
A: See Making the web Accessible. Making sites accessible also makes them more search engine friendly (saves money), makes your pages accessible to the 20% of the population that has some type of disability (so you can make more money) and it’s the law in many places.

Q: Define what web standards mean to you? How do you implement web standards?

Q: In CSS, how can you make a form elments background-color change when the user is entering text? will this work in all browsers?

Q: How can you target an element in your HTML using the DOM?

 
 

Web Developer Resume Screening May 26, 2007

Filed under: Web Development — Estelle Weyl @ 7:02 pm

How to filter through resumes to find good Web Developer applicants

What makes a good web developer these days? An alphabet soup of skills that are simply an effort at search engine optimization for Monster.com, HotJobs or Dice? Don’t waste your time and the applicant’s time by bringing them in for a three hour interview unless you know there is a chance of a good match. Do a phone screen first. It will save you a lot of time and frustration. Before you call, however, you should review not only their resume, but their portfolio of work as well.

Web Developer Resume & Portfolio Screening

When reviewing a resume, use the resume as a guideline of possible skills, not gospel. In deciding who to interview and when to pass, check the resume for stated skills and match that skill set with the skill set displayed in a review of the sites the applicant coded. An understated resume that shows matching skills should be considered as much, if not more, than an overstated resume that shows those same skills. Don’t think a woman is less qualified than a man simply because her resume is modest because his may in fact be exaggerated.

The question has to be, "does the person know how to code correctly?" In reviewing an applicants portfolio there are certain indicators that display whether or not the applicant knows what they are talking about.

  • Elements coded in capital letters or mixed syntax
    <P><A Href="Link.html">Click me</a></P>
    Skip this candidate
    correct: <p><a href="link.html">Click me</a></p>
  • Overlapping elements
    <strong>Hi, my name is <em>estelle</strong></em>
    If it happens once, and otherwise the candidate looks good, it may show a sloppy error, but otherwise the applicant may know how to code.. If the code generally looks like the above, get the shredder!
    correct: <strong>Hi, my name is <em>estelle</em></strong>
  • Gratuitous use of table layouts, frames and flash navigation
    <table><tr><td>&bull;</td><td>should be a list</td></tr></table>
    If the applicant shows no samples of semantic navigation, or displays no samples of tableless layout, then take a look at your other applicants.  If generally everything is semantic, with little exceptions, consider the applicant’s client: sometimes clients insist on development methods. If it’s common, then the applicant doesn’t understand semantic markup and you should pass.
    correct: <ul><li>should be a list</li></ul>
  • Sloppy, pointless CSS
    a {text-align: left; margin: 10px;} // links are default inline elements.
    Take a look at the CSS, not just the HTML. You will likely find errors. The erroneous application of margin on an inline element if it occurs once may be the sloppiness of not cleaning up code or leaving in some CSS from a previous element.  If the style sheet shows a lack of understanding the difference between inline and block elements, doesn’t grasp positioning or floating, move on. If they really know CSS, and they are just sloppy with small clients, then keep reviewing the candidate. If they are both sloppy and have limited knowledge, you can find better.
    better: a {display: block; float: left; margin: 10px;}
  • Abuse of inline javascript event handlers
    <a href="javascript:void()" onmouseover="document.images[0].src=’on.gif’" onmouseout="document.images[0].src=’off.gif’"><img … /></a>
    Give bonus points to those who separate behavior (javascript) from structure (html). Take away points (or throw out the resume) or those who use links for presentation, as in the above sample.
    Separating behavior and structure can be taught. But, in the example above could have been done purely with css. If that is the crap they display, toss their resume: they are not even trying. If you see multiple href="#", or href="javascript:void()", then Next!
    better: <div id="myImg"><img ... /></div> with the content and background controlled via CSS
  • Missing doctypes, two xml prologs, conflicting encoding (xml prolog and meta charset)
    <html><head><title>Untitled Document</title></head>
    Value an applicant who declares the wrong doctype over one who doesn’t declare a doctype at all. Value an applicant who declares an inappropriate charset over one who doesn’t declare a character set. The right answer can be taught more easily that teaching someone to care about web standards.
  • Non-breaking space and br alignments
    <br />&nbsp;<br />&nbsp;
    Web developers should be held completely responsible for the shell of their pages: the templates. In shell of page, using markup for presentation means the applicant isn’t trying to code well. If you find this coding style in the content of the page, and not the guts and the template portion of the site is correctly coded, assume they know how to code and that their client is responsible for the poor content maintenance. Clients will update their own content, and they do the screwiest things.
  • Overreliance of WYSIWYG Editors
    .style1 {color: #ff0000;}
    .style2 {color: #ff0000; font-weight: bold;}

    There is nothing wrong with using Dreamweaver, but you don’t want to hire someone who relies on it. If all javascript functions in the applicants code start with MM, such as MM_showHideLayers, or styles are named in order from style1, style2 .... style65, then they are using Dreamweaver as a crutch and don’t actually know how to code CSS or JavaScript (and perhaps not even XHTML).

Valid Excuses for Samples of Questionable Code

  • Client’s Budget:
    When looking at a sample of code, consider who the site is for. If the site is for a large corporation with funding, be a little stricter in analyzing the code. If the site is built for a small client on a pay per hour basis, consider being a little more lenient. When building sites for small clients, developers may cut corners a few ways to save them money. For example, they may not spend the time cleaning up or commenting the CSS. While you may want to pass on someone who repeats "text-align: left;" 16 times, since it should have been set as the outer element, don’t hold someone who puts three extraneous "text-align: right;"s at major fault.
  • UED or Designer Specifications may have been questionable :
    I coded a site for a designer who created a different layout for the content of every page. While I used an external style sheet for the shell of the page, I used inline styles for the wacky positioning of images within the page. While I should have removed inline styles and create classes, the classes would never have been re-used, the client was on a budget and the graphic designer was going to have me move the images around anyhow.  Your applicant may have similar clients.  I thought it best not to spend my time or the client’s money cleaning up the CSS.
  • Someone else is maintaining the content:
    Sometimes clients maintain their content which can be the cause of bad code. In the shell of the document (the template), if there is mixed case XHTML that’s bad since that is most likely definitely the developers mark. However, if the template code looks great, and only the content is coded like crap, give the applicant the benefit of the doubt.  Perhaps it was being maintained by the client rather than the coder. You may find some mso=normal’s (don’t you love microsoft), unclosed <p> and <li> in the code. These may be signs that the applicant’s clients are maintaining their own pages or using CMS. One of my sites has a table layout for the home page since I was unable to get the client to understand that WYSIWYG editors render pages differently than actual browsers.  Other than the home page the site is well coded, but that home page currently has 30 instances of <p style="margin:0; padding: 0;">&nbsp;</p>.
  • Useless Flash and other Tacky Design elements:
    Sometimes clients insist on flash navigation or intros. If the applicant’s portfolio samples all have flash navigation and few or no samples of semantic navigation, skip the candidate. However, if a few of their sites have flash intros or navs, but it’s evident that they know how to do a standards compliant unordered list navigation from other sites, then don’t hold a flash component against the applicant.

In conclusion, if someone obviously doesn’t know what they’re doing, don’t bother interviewing them. However, if the only crap code you see is the html of their portfolio ("the cobbler’s children have no shoes"), and they show some examples that show that they can definitely be up to par, then do a phone screen.

Note: See also my list of interview questions for web developers.

 
 

IE7 only CSS hacks: Examples May 21, 2007

Filed under: CSS (including hacks), IE7, Web Development — Estelle Weyl @ 12:56 am

Examples of Hacks described in IE7 only CSS Hacks: Explained

This blog entry is the companion page to IE7 only CSS Hacks: Explained which elaborates on how and why these hacks work. Feel free to open this page up in IE7, IE6, Opera and Firefox on the PC, and Safari and Opera on the Mac.


</p> <div lang="en" align="left"> <!-- useless comment --></p> <div> <h2>The Star(*) hack</h2> <p class="starHack">body>div .myClass { *color: #CC33CC; }</p> <h2>The conditional comment</h2> <p class="conditional"> &lt;!&#8211;[if IE 7]&gt;<br /> &lt;style type=&quot;text/css&quot;&gt;<br /> p.conditional {color: #CC33CC;}<br /> &lt;/style&gt;<br /> &lt;![endif]&#8211;&gt;</p> <h2>The LANG filter</h2> <p class="item">.item {color: #000000;}<br /> html&gt;div .item {color: #CC33CC;}<br /> *:lang(en) .item{color: #666666;}<br /> .item:empty {color: #666666 !important} </p> <p>&lt;div lang=&quot;en&quot;&gt;<br /> &lt;p class=&quot;item&quot;&gt;<br /> This will purple in IE7, grey in Firefox and black in IE6</p> <h2>Triple X Hack</h2> <p class="testx" id="testy">.testx { color: #000000; }<br /> p[id$=&quot;testy&quot;] { color:#cc33cc; }<br /> p[id$=&quot;testy&quot;]:not([class=&quot;xxx&quot;]) { color:#666666; }<br /> @media all and (min-width:0px) { p[id$=&quot;testy&quot;] { color:#aaaaaa; } }</p> <p>This will purple in IE7, grey in Firefox and black in IE6</p> <h2 id="case">The Case Sensitive Attribute Hack</h2> <p class="casesensitive">p.casesensitive {color: #000000;} <br /> div[align~=left] p.casesensitive {color: #cc33cc;}<br /> <br /> div[align~=LEFT] p.casesensitive {color: #666666;} </p> <p class="casesensitive">&lt;div align=&quot;left&quot;&gt; &lt;p class=&quot;casesensitive&quot;&gt;<br /> This will purple in IE7, grey in Firefox and black in IE6&lt;/p&gt;</p> <h2>Aimsterloo Hack<br /> a.k.a.<br /> First Child Comment Hack</h2> <p class="fchild">p.fchild {color: #000000;}<br /> html&gt;div p.fchild {<span class="casesensitive">color: #cc33cc;</span>}<br /> div :first-child p.fchild {color: #666666;} </p> <p>&lt;div&gt;&lt;!&#8211; useless comment &#8211;&gt;&lt;div&gt;&lt;p class=&quot;fchild&quot;&gt;<br /> The div should be the first child of the div, but in IE it isn&#8217;t&#8230; </p> </div> </div> <p>