online advertising

A Web Standards Checklist – How to make a proper website

(11 votes, average: 5.00 out of 5)
Loading ... Loading ...

If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!

A web standards checklist

The term web standards can mean different things to different people. For some, it is ‘table-free sites’, for others it is ‘using valid code’. However, web standards are much broader than that. A site built to web standards should adhere to standards (HTML, XHTML, XML, CSS, XSLT, DOM, MathML, SVG etc) and pursue best practices (valid code, accessible code, semantically correct code, user-friendly URLs etc).

In other words, a site built to web standards should ideally be lean, clean, CSS-based, accessible, usable and search engine friendly.

About the checklist

This is not an uber-checklist. There are probably many items that could be added. More importantly, it should not be seen as a list of items that must be addressed on every site that you develop. It is simply a guide that can be used:

- to show the breadth of web standards
- as a handy tool for developers during the production phase of websites
- as an aid for developers who are interested in moving towards web standards

The checklist

1.Quality of code
a. Does the site use a correct Doctype?
b. Does the site use a Character set?
c. Does the site use Valid (X)HTML?
d. Does the site use Valid CSS?
e. Does the site use any CSS hacks?
f. Does the site use unnecessary classes or ids?
g. Is the code well structured?
h. Does the site have any broken links?
i. How does the site perform in terms of speed/page size?
j. Does the site have JavaScript errors?

2. Degree of separation between content and presentation
a. Does the site use CSS for all presentation aspects (fonts, colour, padding, borders etc)?
b. Are all decorative images in the CSS, or do they appear in the (X)HTML?

3. Accessibility for users
a. Are “alt” attributes used for all descriptive images?
b. Does the site use relative units rather than absolute units for text size?
c. Do any aspects of the layout break if font size is increased?
d. Does the site use visible skip menus?
e. Does the site use accessible forms?
f. Does the site use accessible tables?
g. Is there sufficient colour brightness/contrasts?
h. Is colour alone used for critical information?
i. Is there delayed responsiveness for dropdown menus (for users with reduced motor skills)?
j. Are all links descriptive (for blind users)?

4. Accessibility for devices
a. Does the site work acceptably across modern and older browsers?
b. Is the content accessible with CSS switched off or not supported?
c. Is the content accessible with images switched off or not supported?
d. Does the site work in text browsers such as Lynx?
e. Does the site work well when printed?
f. Does the site work well in Hand Held devices?
g. Does the site include detailed metadata?
h. Does the site work well in a range of browser window sizes?

5. Basic Usability
a. Is there a clear visual hierarchy?
b. Are heading levels easy to distinguish?
c. Does the site have easy to understand navigation?
d. Does the site use consistent navigation?
e. Are links underlined?
f. Does the site use consistent and appropriate language?
g. Do you have a sitemap page and contact page? Are they easy to find?
h. For large sites, is there a search tool?
i. Is there a link to the home page on every page in the site?
j. Are visited links clearly defined with a unique colour?

6. Site management
a. Does the site have a meaningful and helpful 404 error page that works from any depth in the site?
b. Does the site use friendly URLs?
c. Do your URLs work without “www”?
d. Does the site have a favicon?

1. Quality of code

1.1 Does the site use a correct Doctype?
A doctype (short for ‘document type declaration’) informs the validator which version of (X)HTML you’re using, and must appear at the very top of every web page. Doctypes are a key component of compliant web pages: your markup and CSS won’t validate without them.

http://www.alistapart.com/articles/doctype/

More:

http://www.w3.org/QA/2002/04/valid-dtd-list.html

http://css.maxdesign.com.au/listamatic/about-boxmodel.htm

http://gutfeldt.ch/matthias/articles/doctypeswitch.html

1.2 Does the site use a Character set?
If a user agent (eg. a browser) is unable to detect the character encoding used in a Web document, the user may be presented with unreadable text. This information is particularly important for those maintaining and extending a multilingual site, but declaring the character encoding of the document is important for anyone producing XHTML/HTML or CSS.

http://www.w3.org/International/tutorials/tutorial-char-enc/

More:

http://www.w3.org/International/O-charset.html

1.3 Does the site use Valid (X)HTML?
Valid code will render faster than code with errors. Valid code will render better than invalid code. Browsers are becoming more standards compliant, and it is becoming increasingly necessary to write valid and standards compliant HTML.

http://www.maxdesign.com.au/presentation/sit2003/06.htm

More:

http://validator.w3.org/

1.4 Does the site use Valid CSS?
You need to make sure that there aren’t any errors in either your HTML or your CSS, since mistakes in either place can result in botched document appearance.

http://www.meyerweb.com/eric/articles/webrev/199904.html

More:

http://jigsaw.w3.org/css-validator/

1.5 Does the site use any CSS hacks?
Basically, hacks come down to personal choice, the amount of knowledge you have of workarounds, the specific design you are trying to achieve.

http://www.mail-archive.com/wsg@webstandardsgroup.org/msg05823.html

More:

http://css-discuss.incutio.com/?page=CssHack

http://css-discuss.incutio.com/?page=ToHackOrNotToHack

http://centricle.com/ref/css/filters/

1.6 Does the site use unnecessary classes or ids?
I’ve noticed that developers learning new skills often end up with good CSS but poor XHTML. Specifically, the HTML code tends to be full of unnecessary divs and ids. This results in fairly meaningless HTML and bloated style sheets.

http://www.clagnut.com/blog/228/

1.7 Is the code well structured?
Semantically correct markup uses html elements for their given purpose. Well structured HTML has semantic meaning for a wide range of user agents (browsers without style sheets, text browsers, PDAs, search engines etc.)

http://www.maxdesign.com.au/presentation/benefits/index04.htm

More:

http://www.w3.org/2003/12/semantic-extractor.html

1.8 Does the site have any broken links?
Broken links can frustrate users and potentially drive customers away. Broken links can also keep search engines from properly indexing your site.

More:

http://validator.w3.org/checklink

1.9 How does the site perform in terms of speed/page size?
Don’t make me wait… That’s the message users give us in survey after survey. Even broadband users can suffer the slow-loading blues.

http://www.websiteoptimization.com/speed/

1.10 Does the site have JavaScript errors?
Internet Explore for Windows allows you to turn on a debugger that will pop up a new window and let you know there are javascript errors on your site. This is available under ‘Internet Options’ on the Advanced tab. Uncheck ‘Disable script debugging’.

2. Degree of separation between content and presentation

2.1 Does the site use CSS for all presentation aspects (fonts, colour, padding, borders etc)?
Use style sheets to control layout and presentation.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-style-sheets

2.2 Are all decorative images in the CSS, or do they appear in the (X)HTML?
The aim for web developers is to remove all presentation from the html code, leaving it clean and semantically correct.

http://www.maxdesign.com.au/presentation/benefits/index07.htm

3. Accessibility for users

3.1 Are “alt” attributes used for all descriptive images?
Provide a text equivalent for every non-text element

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-text-equivalent

3.2 Does the site use relative units rather than absolute units for text size?
Use relative rather than absolute units in markup language attribute values and style sheet property values’.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-relative-units

More:

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-relative-units

http://www.clagnut.com/blog/348/

3.3 Do any aspects of the layout break if font size is increased?
Try this simple test. Look at your website in a browser that supports easy incrementation of font size. Now increase your browser’s font size. And again. And again… Look at your site. Does the page layout still hold together? It is dangerous for developers to assume that everyone browses using default font sizes.

3.4 Does the site use visible skip menus?

A method shall be provided that permits users to skip repetitive navigation links.

http://www.section508.gov/index.cfm?FuseAction=Content&ID=12

Group related links, identify the group (for user agents), and, until user agents do so, provide a way to bypass the group.

http://www.w3.org/TR/WCAG10-TECHS/#tech-group-links

…blind visitors are not the only ones inconvenienced by too many links in a navigation area. Recall that a mobility-impaired person with poor adaptive technology might be stuck tabbing through that morass.

http://joeclark.org/book/sashay/serialization/Chapter08.html#h4-2020

More:

http://www.niehs.nih.gov/websmith/508/o.htm

3.5 Does the site use accessible forms?
Forms aren’t the easiest of things to use for people with disabilities. Navigating around a page with written content is one thing, hopping between form fields and inputting information is another.

http://www.htmldog.com/guides/htmladvanced/forms/

More:

http://www.webstandards.org/learn/tutorials/accessible-forms/01-accessible-forms.html

http://www.accessify.com/tools-and-wizards/accessible-form-builder.asp

http://accessify.com/tutorials/better-accessible-forms.asp

3.6 Does the site use accessible tables?
For data tables, identify row and column headers… For data tables that have two or more logical levels of row or column headers, use markup to associate data cells and header cells.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-table-headers

More:

http://www.bcc.ctc.edu/webpublishing/ada/resources/tables.asp

http://www.accessify.com/tools-and-wizards/accessible-table-builder_step1.asp

http://www.webaim.org/techniques/tables/

3.7 Is there sufficient colour brightness/contrasts?
Ensure that foreground and background colour combinations provide sufficient contrast when viewed by someone having colour deficits.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-colour-contrast

More:

http://www.juicystudio.com/services/colourcontrast.asp

3.8 Is colour alone used for critical information?
Ensure that all information conveyed with colour is also available without colour, for example from context or markup.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-colour-convey

There are basically three types of colour deficiency; Deuteranope (a form of red/green colour deficit), Protanope (another form of red/green colour deficit) and Tritanope (a blue/yellow deficit- very rare).

More:

http://colourfilter.wickline.org/

http://www.toledo-bend.com/colourblind/Ishihara.html

http://www.vischeck.com/vischeck/vischeckURL.php

3.9 Is there delayed responsiveness for dropdown menus?
Users with reduced motor skills may find dropdown menus hard to use if responsiveness is set too fast.

3.10 Are all links descriptive?
Link text should be meaningful enough to make sense when read out of context – either on its own or as part of a sequence of links. Link text should also be terse.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-meaningful-links

4. Accessibility for devices.

4.1 Does the site work acceptably across modern and older browsers?

Before starting to build a CSS-based layout, you should decide which browsers to support and to what level you intend to support them.

http://www.maxdesign.com.au/presentation/process/index_step01.cfm

4.2 Is the content accessible with CSS switched off or not supported?
Some people may visit your site with either a browser that does not support CSS or a browser with CSS switched off. In content is structured well, this will not be an issue.

4.3 Is the content accessible with images switched off or not supported?
Some people browse websites with images switched off – especially people on very slow connections. Content should still be accessible for these people.

4.4 Does the site work in text browsers such as Lynx?
This is like a combination of images and CSS switched off. A text-based browser will rely on well structured content to provide meaning.

More:

http://www.delorie.com/web/lynxview

4.5 Does the site work well when printed?
You can take any (X)HTML document and simply style it for print, without having to touch the markup.

http://www.alistapart.com/articles/goingtoprint/

More:

http://www.d.umn.edu/itss/support/Training/Online/webdesign/css.html#print

4.6 Does the site work well in Hand Held devices?
This is a hard one to deal with until hand held devices consistently support their correct media type. However, some layouts work better in current hand-held devices. The importance of supporting hand held devices will depend on target audiences.

4.7 Does the site include detailed metadata?
Metadata is machine understandable information for the web

http://www.w3.org/Metadata/

Metadata is structured information that is created specifically to describe another resource. In other words, metadata is ‘data about data’.

4.8 Does the site work well in a range of browser window sizes?
It is a common assumption amongst developers that average screen sizes are increasing. Some developers assume that the average screen size is now 1024px wide. But what about users with smaller screens and users with hand held devices? Are they part of your target audience and are they being disadvantaged?

5. Basic Usability
5.1 Is there a clear visual hierarchy?
Organise and prioritise the contents of a page by using size, prominence and content relationships.

http://www.great-web-design-tips.com/web-site-design/165.html

5.2 Are heading levels easy to distinguish?
Use header elements to convey document structure and use them according to specification.

http://www.w3.org/TR/WCAG10/wai-pageauth.html#tech-logical-headings

5.3 Is the site’s navigation easy to understand?
Your navigation system should give your visitor a clue as to what page of the site they are currently on and where they can go next.

http://www.1stsitefree.com/design_nav.htm

5.4 Is the site’s navigation consistent?
If each page on your site has a consistent style of presentation, visitors will find it easier to navigate between pages and find information

http://www.juicystudio.com/tutorial/accessibility/navigation.asp

5.5 Does the site use consistent and appropriate language?
The use of clear and simple language promotes effective communication. Trying to come across as articulate can be as difficult to read as poorly written grammar, especially if the language used isn’t the visitor’s primary language.

http://www.juicystudio.com/tutorial/accessibility/clear.asp

5.6 Does the site have a sitemap page and contact page? Are they easy to find?
Most site maps fail to convey multiple levels of the site’s information architecture. In usability tests, users often overlook site maps or can’t find them. Complexity is also a problem: a map should be a map, not a navigational challenge of its own.

http://www.useit.com/alertbox/20020106.html

5.7 For large sites, is there a search tool?
While search tools are not needed on smaller sites, and some people will not ever use them, site-specific search tools allow users a choice of navigation options.

5.8 Is there a link to the home page on every page in the site?
Some users like to go back to a site’s home page after navigating to content within a site. The home page becomes a base camp for these users, allowing them to regroup before exploring new content.

5.9 Are links underlined?
To maximise the perceived affordance of clickability, colour and underline the link text. Users shouldn’t have to guess or scrub the page to find out where they can click.

http://www.useit.com/alertbox/20040510.html

5.10 Are visited links clearly defined?
Most important, knowing which pages they’ve already visited frees users from unintentionally revisiting the same pages over and over again.

http://www.useit.com/alertbox/20040503.html

6. Site management

6.1 Does the site have a meaningful and helpful 404 error page that works from any depth in the site?
You’ve requested a page – either by typing a URL directly into the address bar or clicking on an out-of-date link and you’ve found yourself in the middle of cyberspace nowhere. A user-friendly website will give you a helping hand while many others will simply do nothing, relying on the browser’s built-in ability to explain what the problem is.

http://www.alistapart.com/articles/perfect404/

6.2 Does the site use friendly URLs?
Most search engines (with a few exceptions – namely Google) will not index any pages that have a question mark or other character (like an ampersand or equals sign) in the URL… what good is a site if no one can find it?

http://www.sitepoint.com/article/search-engine-friendly-urls

One of the worst elements of the web from a user interface standpoint is the URL. However, if they’re short, logical, and self-correcting, URLs can be acceptably usable

http://www.merges.net/theory/20010305.html

More:

http://www.sitepoint.com/article/search-engine-friendly-urls

http://www.websitegoodies.com/article/32

http://www.merges.net/theory/20010305.html

6.3 Does the site’s URL work without “www”?
While this is not critical, and in some cases is not even possible, it is always good to give people the choice of both options. If a user types your domain name without the www and gets no site, this could disadvantage both the user and you.

6.4 Does the site have a favicon?

A Favicon is a multi-resolution image included on nearly all professionally developed sites. The Favicon allows the webmaster to further promote their site, and to create a more customized appearance within a visitor’s browser.

http://www.favicon.com/

Favicons are definitely not critical. However, if they are not present, they can cause 404 errors in your logs (site statistics). Browsers like IE will request them from the server when a site is bookmarked. If a favicon isn’t available, a 404 error may be generated. Therefore, having a favicon could cut down on favicon specific 404 errors. The same is true of a ‘robots.txt’ file.

Making Web Page Fonts Consistent and Uniform

(No Ratings Yet)
Loading ... Loading ...

Is it disturbing to you when every other Web page you visit has a different font size?. One web page’s font is too small, and another web page’s fonts are too big… Well here’s a way to fix that and set each web page’s fonts to just the size you want.

In Internet Explorer, select: Tools-Internet Options, choose the General tab, click the Accessibility button, and check Ignore font sizes specified on Web pages (the wording varies depending on your IE version).

In Netscape 6 and 7, choose Edit-Preferences, select Fonts (double-click Appearance if you don’t see ‘Fonts’ listed), and then either check Use my default fonts or uncheck Allow documents to use other fonts, depending on your version (the wording of these choices also varies).

Now all Web page fonts should be of uniform size on all pages.

55 Reasons to Design in XHTML-CSS

(1 votes, average: 5.00 out of 5)
Loading ... Loading ...

In no particular order 55 reasons for me to do “tableless” websites using valid XHTML for markup, CSS for layout and Flash sparingly, only as an ingredient. By tableless I mean avoiding tables (or a tagsoup of unnecessary divs substituting table trs and tds) for layout purposes and aiming towards as semantic markup as possible. Some of the reasons are “over HTML”, some “over Flash full monty” and some over both.

I know this topic has been discussed a plenty, I just needed to reaffirm myself :)

Here we go:

  1. You can get free links from showcase sites like zengarden, stylegala, cssimport or cssbeauty
  2. You don’t have to spend extra thought and time deciding on styling the mark up of your document (upper- or lowercase, quotes or no quotes on attributes)
  3. You don’t need to spend extra thought on which tags should be closed and which can (or should) be left open
  4. You “help” the search engines to deliver more relevant content using semantic markup
  5. You can save in bandwidth costs and visitors will see them faster by making slimmer pages
  6. It’s going to be easier for you to switch to XHTML 2.0 which will give you more semantic tools
  7. Once you’ve practised enough, coding pages becomes a whole lot simpler and faster than any table/tr/td tagsoup
  8. When the coding is faster you can spend more time on thinking about the user experience
  9. Thinking about semantics of a document helps you to make design and information architecture decisions
  10. You can quickly make a dummy site to test your sites information architecture and append a look and feel later with only minor code changes
  11. You can do the design after most of the backend is done which will help your client (or boss) to think realistically about how much work is still needed
  12. It’s possible to link directly to your content pages (compared to Flash)
  13. browser controls like text-size and back and forward buttons work (compared to Flash)
  14. Redesigns and realigns over the whole site are simpler
  15. it’s simpler to make small last minute changes to your designs
  16. Clean markup makes it easier or even unnecessary to build a CMS
  17. Clean markup makes it easier for another developer to jump on board
  18. You can make the backend almost totally independently from the frontend design, by completely different person
  19. You have plenty of ways to play with the markup trying to optimize for search engines, without affecting visible layout
  20. You have total control on print layouts of your pages
  21. Your sites are automatically accessible to all kinds of browsers
  22. Promoting web standards will help your work in the future, not having to code differently to each browser
  23. With all elemets closed you mark up look cleaner
  24. Well-formed code ensures your site works in more browsers
  25. Well-formed code would help browser coders to spend more time on useful features than rendering engines that try to understand borken code
  26. Your website will work in future browsers
  27. Your website works in mobile (and other new) devices
  28. You learn the basics of XML which has many other uses
  29. CSS files are saved in browser cache for fast retrieval and less bandwidth use
  30. Your documents are easy to convert back and forth another format using XSLT
  31. Thinking semantics makes you think more about the content
  32. Learning semantics makes you appreciate organization and write your other documents (even emails) in more organized way
  33. You can write new technologies in your CV or portfolio
  34. Modern browsers render a valid document faster
  35. You feel better about yourself when you are making sites “the right way”
  36. They are doing it: Dan Cederholm, Jeffrey Zeldman, Jason Santa Maria, Shaun Inman, Cameron Moll, Douglas Bowman, Dave Shea
  37. You will belong in a “movement”, make good contacts etc.
  38. You learn to appreciate newer browsers which makes for more competition and later for better browsers
  39. Blink tag is gone
  40. Strict coding makes you learn to see mistakes quicker
  41. You can aim to making some money writing a book about it
  42. There are more job opportunities if you know these new ways
  43. You learn better to understand how a browser works
  44. You can use hacks and techniques with cool names like “be nice to Opera”
  45. you start to care more about metadata, document and character types
  46. With more people making slimmer pages, the amount of data moving in the whole web will be smaller and all connections faster
  47. XHTML has a cooler name than HTML
  48. There are more people thinking about the advantages and disadvantages and coding tricks of XHTML which makes for a bigger learning forum
  49. You can use basically same markup template for many different websites
  50. Learning to read and write it fast makes it possible to use cheaper tools (notepad)
  51. Google knows this:
    • 4,380,000 xhtml better than html > 4,370,000 html better than xhtml
    • 206 “xhtml is better than html” > 87 “html is better than xhtml”
    • 2,130,000 xhtml sucks < 10,300,000 html sucks
  52. When all browsers start to understand the correct MIME-type (xml), you don’t have to convert all your websites from html, just to switch to correct MIME
  53. By more people using xhtml you ensure that in the future IE will need to understand the correct MIME-type
  54. Accessibility is enforced with requiring Alt attribute for images
  55. There just aren’t this many reasons to use HTML or entirely Flash instead

Ten more CSS tricks you may not know

(No Ratings Yet)
Loading ... Loading ...

Ten CSS Tricks You May Not Know has proven to be such a success that we decided it was time to offer you ten more CSS tricks that you may not know.

1. Block vs. inline level elements

Nearly all HTML elements are either block or inline elements. The characteristics of block elements include:

  • Always begin on a new line
  • Height, line-height and top and bottom margins can be manipulated
  • Width defaults to 100% of their containing element, unless a width is specified

Examples of block elements include <div>, <p>, <h1>, <form>, <ul> and <li>. Inline elements on the other hand have the opposite characteristics:

  • Begin on the same line
  • Height, line-height and top and bottom margins can’t be changed
  • Width is as long as the text/image and can’t be manipulated

Examples of inline elements include <span>, <a>, <label>, <input>, <img>, <strong> and <em>.

To change an element’s status you can use display: inline or display: block. But what’s the point of changing an element from being block to inline, or vice-versa? Well, at first it may seem like you might hardly ever use this, but in actual fact this is a very powerful technique, which you can use any time you want to:

  • Have an inline element start on a new line
  • Have a block element start on the same line
  • Control the width of an inline element (particularly useful for navigation links)
  • Manipulate the height of an inline element
  • Set a background colour as wide as the text for block elements, without having to specify a width

2. Another box model hack alternative

The box model hack is used to fix a rendering problem in pre-IE 6 browsers on PC, where by the border and padding are included in the width of an element, as opposed to added on. A number of CSS-based solutions have been put forward to remedy this, so here’s another one which we really like:

padding: 2em;
border: 1em solid green;
width: 20em;
width/**/:/**/ 14em;

The first width command is read by all browsers; the second by all browsers except IE5.x on PC. Because the second command comes second it takes precedence over the first – any command that comes second will always override a preceding command. So, how does all this work?

By placing empty comment tags (/**/) before the colons, IE5.0 will ignore the command. Likewise, by placing these empty comment tags after the colon, IE5.5 will ignore the command. By using these two rules in conjunction with each other, we can hide the command from all of IE5.x.

3. Minimum width for a page

A very handy CSS command that exists is the min-width command, whereby you can specify a minimum width for any element. This can be particularly useful for specifying a minimum width for a page.

Unfortunately, IE doesn’t understand this command, so we’ll need to come up with a new way of making this work in this browser. First, we’ll insert a <div> under the <body> tag, as we can’t assign a minimum width to the <body>:

<body>
<div id="container">

Next we create our CSS commands, so as to create a minimum width of 600px:

#container
{
min-width: 600px;
width:expression(document.body.clientWidth < 600? "600px": "auto" );
}

The first command is the regular minimum width command; the second is a short JavaScript command that only IE understands. Do note though, this command will cause your CSS document to invalidate so you may prefer to insert it into the head of each HTML document to get round this.

You might also want to combine this minimum width with a maximum width:

#container
{
min-width: 600px;
max-width: 1200px;
width:expression(document.body.clientWidth < 600? "600px" : document.body.clientWidth > 1200? "1200px" : "auto");
}

4. IE and width & height issues

IE has a rather strange way of doing things. It doesn’t understand the min-width and min-height commands, but instead interprets width and height as min-width and min-height – go figure!

This can cause problems, because we may need boxes to be resizable should more text need to go in them or should the user resize text. If we only use the width and height commands on a box then non-IE browsers won’t allow the box to resize. If we only use the min-width and min-height commands though then we can’t control the width or height in IE!

This can be especially problematic when using background images. If you’re using a background image that’s 80px wide and 35px high, then you’ll want to make sure that the default size for a box using this image is exactly 80 x 35px. However, if users resize the text then the box size will need to expand gracefully.

To resolve this problem, you can use the following code for a box with class="box":

.box
{
width: 80px;
height: 35px;
}

html>body .box
{
width: auto;
height: auto;
min-width: 80px;
min-height: 35px;
}

All browsers will read through the first CSS rule but IE will ignore the second rule because it makes use of the child selector command. Non-IE browsers will read through the second one and will override the values from the first rule because this CSS rule is more specific, and CSS rules that are more specific always override those that are less specific.

5. Text-transform command

One of the lesser known, but really useful CSS commands is the text-transform command. Three of the more common values for this rule are: text-transform: uppercase, text-transform: lowercase and text-transform: capitalize. The first rule turns all characters into capital letters, the second turns them all into small letters, and the third makes the first letter of each word capitals.

This command is incredibly useful to help ensure consistency in style across an entire website, particularly if there a number of content editors. Say for example your style guide dictates that words in headings must always begin with capital letters. To ensure that this is always the case, use text-transform: capitalize. Even if site editors forget about the capitalisation, their mistake won’t show up on the website.

It’s also preferable to use text-transform: uppercase to capitalise words, as screen readers may pronounce shorter words in capital letters as acronyms. A great example of this is ‘CONTACT US’, which is pronounced as ‘contact U S’ by some screen readers.

6. Disappearing text or images in IE?

IE has a very strange bug where text or background images sometimes disappears from sight. These items are still actually there, and if you highlight everything on screen or hit refresh they’ll often re-appear. Kind of strange, huh?

This problem mostly occurs on background images and on text next to a floated element. To remedy the problem, simply insert position: relative into the CSS command for the disappearing element, and for some bizarre reason that’ll usually fix the problem. If this doesn’t work (it sometimes doesn’t), assign a width to the offending element in the CSS and that should fix the problem.

7. Invisible text

Sometime you may actually want to make text invisible. Invisible text can be especially useful for screen reader users, perhaps to assign a label to a form item or insert a heading ahead of a section. Don’t want to change the visual appearance by inserting these? Make them invisible and no one using a visual browser knows that they’re there.

You may also want to make text invisible if using a print or handheld CSS file, as some information may not need to be displayed on either of these mediums (see below for more on this).

To make text invisible you can use display: none – easy! This works fine for hiding text from handhelds (if CSS is supported) and printed web pages, but isn’t so great for many screen readers. Screen readers are now becoming too clever for their own good, and some will actually ignore the any text that has the rule display: none assigned to it.

For screen readers users therefore, a new approach is needed: position: absolute; left: -9000px. This basically takes the text and positions it 9000px to the left of the left edge of the screen, essentially making it invisible.

8. CSS document for handhelds

A separate CSS document can be created for PDAs and mobile phones, and only activated when one of these devices is being used to access your site. More and more websites are creating separate CSS documents for printing, so web pages automatically become print-friendly when users choose to print them. You can also do the same for handheld devices.

The following command is used to call up the CSS document for handhelds:

<link type="text/css" rel="stylesheet" href="handheldstyle.css" media="handheld" />

CSS commands in the handheld CSS file override any equivalent commands in the main CSS document. So, what commands should you place in this file?

Ideally, you want handheld web users to avoid having to scroll across. To test this, open up your website in a regular browser window and resize it to 150px in width. Then, open up your main CSS file and insert some new commands at the very bottom of the document. The commands you place here should adjust the layout of the website so that it doesn’t require horizontal scrolling at a 150px width. Then, open up a new document, cut and paste these new commands over, and save it as handheldstyle.css (or whatever name you want to give it).

What your website offers to handheld web users should be quite different to what it offers on traditional web browsers, as the user experience is quite different. For further information, a book such as Handheld Usability is a great read.

9. 3-d push button effect

Back in the early days of the web, 3-d buttons that appeared to become pushed in when moused over were all the rage. At that time, this could only be achieved through images and JavaScript, but now with the advent of CSS we can go all retro and re-create the desired effect:

The main CSS commands you’ll need are:

a {
display: block;
border: 1px solid;
border-color: #aaa #000 #000 #aaa;
width: 8em;
background: #fc0;
}

a:hover
{
position: relative;
top: 1px;
left: 1px;
border-color: #000 #aaa #aaa #000;
}

Aside from these commands, you can insert any other commands to achieve the desired presentation effect – the only limit is your imagination!

10. Same navigation code on every page

Most websites highlight the navigation item of the user’s location in the website, to help users orientate themselves. This is a fundamental requirement for basic usability, but can be a pain as you’ll need to tweak the HTML code behind the navigation for each and every page. So can we have the best of both worlds? Is it possible to have the navigation highlighted on every page, without having to tweak the HTML code on each and every page? Of course it is…

First of all, you’ll need to assign a class to each navigation item:

<ul>
<li><a href="#" class="home">Home</a></li>
<li><a href="#" class="about">About us</a></li>
<li><a href="#" class="contact">Contact us</a></li>
</ul>

You’ll then need to insert an id into the <body> tag. The id should be representative of where users are in the site and should change when users move to a different site section. When in ‘Home’ it should read <body id="home">, in ‘About Us’ it should be <body id="about"> and in ‘Contact Us’ <body id="contact">.

Next, you create a new CSS rule:

#home .home, #about .about, #contact .contact
{
commands for highlighted navigation go here
}

This basically creates a rule that only takes effect when class="home" is contained within id="home", and when class="about" is in id="about" and class="contact" is in id="contact". These situations will only occur when the user is in the appropriate site section, seamlessly creating our highlighted navigation item.

Internet Explorer & CSS issues

(No Ratings Yet)
Loading ... Loading ...

Trying to get CSS-based websites to look the same across all browsers can often be difficult. Many of the problems however lie with Internet Explorer implementing CSS commands differently to other, more standards compliant browsers. All is not lost, however, as many of the differences you see across browsers are caused by the same Internet Explorer CSS issues…

1. Page elements are narrower in Internet Explorer

Perhaps the most famous IE and CSS problem is Internet Explorer’s misinterpretation of the CSS box model, which can cause page elements to be narrower in IE. Every HTML element is essentially a box, the width of which is the total of its margin, border, padding and content area. Imagine the following CSS rule:

div {
margin: 5em;
padding: 4em;
border: 1em solid green;
width: 30em
}

This means that each div is 50em wide in total. This amount is made up of a 30em wide content area, and a 4em padding, 1em border and 5em (invisible) margin on both the left and right sides.

In IE however, the border and padding are included in the width of the content, as opposed to added on. In IE therefore, the width of the content is only 20em (30em less 5em padding and border on either side), and the total width of the div is just 40em.
This CSS box model problem occurs in IE5.x, and can occur in IE6, depending on how you declare the ISO value in the HTML code. There are two ways of doing this:

  • <?xml version="1.0" encoding="iso-8859-1"?>
  • <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

The first command is placed on the very first line of the HTML document and the second can be placed anywhere within the <head>. In order for XHTML pages to validate it’s compulsory to use one of these commands. The W3C recommends using the first command as the second will be phased out in the future.

By using the first command however, Internet Explorer 6 will render the CSS box model incorrectly, just like in version 5 browsers. To fix the box model problem, you’ll need to insert a CSS hack to send different width values to different browsers. The CSS hack you use will depend on which ISO value you use, and therefore which versions of IE are rendering the box model incorrectly.

To fix up only IE5.x, use the following CSS commands:

div {
margin: 5em;
padding: 4em;
border: 1em solid green;
width/**/:/**/ 40em;
width: 30em
}

To fix up all versions of IE, use these CSS commands:

div {
margin: 5em;
padding: 4em;
border: 1em solid green;
width: 40em
}
html>body div {
width: 30em
}

(See the article, CSS hacks & browser detection for more on these hacks.)

2. Text spilling out of its container in non-IE browsers

Internet Explorer, unlike other browsers, will expand borders and background colours so text doesn’t spill out of its containing element.

If you’re going to view this in Internet Explorer, the box should look fine. In all other browsers the text is spilling out of the right-hand side of the box. The box has been assigned class="box" and has the following CSS commands assigned to it: .box {
width: 40px;
border: 2px solid #781351;
padding: 3px;
background: #d7b9c9;
white-space: nowrap
}

Non-IE browsers will adhere to the width: 40px CSS command, which is why the box doesn’t expand in these browsers. IE instead interprets width as min-width, and therefore expands the box to fit the text (the same applies with height and min-height).

To ensure the text doesn’t spill out of the box in all browsers, you’ll need to use the following CSS rule, in addition to the first one:

html>body .box
{
width: auto;
min-width: 40px
}

IE will ignore this CSS command, as the command has html>body at the front of it (see the article, CSS hacks & browser detection for more on this). As such, this CSS command is only for non-IE browsers. The first CSS rule, width: auto, cancels out the original width rule. The second command, min-width: 40px then assigns a minimum width to the box, so the box will always expand to fit the text.

Check out the box again (you won’t see any difference in Internet Explorer, so open this up in another browser to see the change); Much better!

3. Disappearing background images

IE has a very freaky bug where it likes to make background images (and sometimes even text – particularly if there are floated elements around) disappear. This often happens when you scroll up and down on a web page and you can usually make the background re-appear by refreshing the page.

Obviously you won’t want your site visitors to have to refresh a page to see a background image in full! A freaky solution to this freaky problem is to insert the CSS command, position: relative into the CSS rule containing the background image:

.foo {
background: url(filename.jpg);
position: relative
}

Occasionally this won’t work, so another solution is to assign a width or a height to the element with the background image. You may not want to assign a height or width, so a solution is to assign a height of 1% for Internet Explorer. Because IE interprets height as min-height (see point 2 above) this CSS rule won’t affect the appearance:

.foo {
background: url(filename.jpg);
height: 1%
}
html>body .foo {
height: auto
}

The height: 1% CSS command is cancelled out by the height: auto CSS command. Internet Explorer doesn’t understand html>body, so by inserting this in front of the second CSS rule this whole CSS rule is ignored by IE.

4. Widths only working on IE

Every HTML element is either a block or an inline element. Examples of block elements include <div>, <p>, <h1>, <form> and <li>. Example of inline elements include <span>, <a>, <label>, <strong> and <em>.

One of the characteristics of inline elements is that you can’t change the width of an inline element. The following CSS rule shouldn’t, in theory, work:

span {
width: 100px
}

This CSS rule won’t work, except in Internet Explorer where each span will now have a width of 100px. In every other browser however, the width of the span will simply be the width of the number of characters contained in the element. The solution? Make the span a block level element:

span {
width: 100px;
display: block
}

(Turning the span into a block element will make the width command work in every browser, but it will also make the span begin on a new line. To combat this, you could assign float: left to the span.)

5. Unstyled version of web page appearing in IE

When your website loads up in Internet Explorer, does an unstyled version of the page appear for a second or two, before the styled version kicks in this? If so, your website may be suffering from what’s known as the Flash Of Unstyled Content (or FOUC).

If you’re using the @import directive (e.g. <style type="text/css">@import "styles.css";</style>) to call up your CSS file then this phenomenon may be happening on your website in IE. It’s weird, there’s no logical explanation for it, but this problem obviously needs to be fixed.

The simple solution to this illogical problem is an equally illogical solution – insert either a link or a script element into the header:

  • <script type="text/javascript" src="scripts.js"></script>
  • <link rel="stylesheet" href="styles.css" type="text/css" media="print" />

It doesn’t matter which one you insert (or even if you insert both). If you provide a print stylesheet, using the link element to reference it (as indicated in the example above), then you’ll never see the FOUC phenomenon.

6. Fixed width web page not sitting in centre of window

Got a fixed width website and can’t get it to centrally align in the window in Internet Explorer? Or you can get it to centrally align in IE but not in any other browser? Fear not, it’s not your fault! Unfortunately, the correct way of centrally aligning content through CSS doesn’t actually work in IE:

#container {
width: 770px;
margin: 0 auto
}

The second command, margin: 0 auto, basically gives our containing element an automatic margin on the left and right, thereby positioning the containing element in the centre of the browser window.

IE however, will need slightly different commands to make this work:

body {
text-align: center
}
#container {
width: 770px;
margin: 0 auto;
text-align: left
}

This will then centrally align the container in IE too. To prevent the text from centrally aligning too, we insert text-align: left into the container div.

This article was written by Trenton Moss. Trenton’s crazy about web usability and accessibility – so crazy that he went and started his own web usability and accessibility consultancy to help make the Internet a better place for everyone. He knows an awful lot about the Disability Discrimination Act and spends much of his time working on the world’s most accessible CMS.

Widget Walkthrough

(No Ratings Yet)
Loading ... Loading ...

The first half of this tutorial introduced you to making a rudimentary but functional widget of the sort you can find on Yahoo’s site since its purchase of Konfabulator. In this article, you’ll add the finishing touches to increase its functionality.Widget Walkthrough

The preferences that you created in the first part of this article won’t actually do anything on their own; they’ll need the following JavaScript in order to actually make the required changes:

<action trigger=”onLoad”>
<![CDATA[
function updatepreferences() {
datatextarea.font = preferences.textfontpref.value;
datatextarea.color = preferences.textcolorpref.value;
datatextarea.size = preferences.textsizepref.value;
datatextarea.style = preferences.textstylepref.value;
}
updatepreferences();
]]>
</action>
<action trigger =”onPreferencesChanged”>
updatepreferences();
</action>

As you can see, each action (onLoad and onPreferencesChanged) is contained within its own <action> element. All each line of the updatepreferences() function is doing is setting the attributes of the textarea element, much as CSS would with HTML. I’ve included the opening CDATA tag as we’ll need it for one of the next functions.

Widget Walkthrough – Getting the headlines

Now you need to actually get the news headlines from the BBC web server. To do this, you’ll need to make use of the URL widget engine object:

function getdata() {
var url = new URL();

url.location =
“http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/
technology/rss.xml”;
feeddata = url.fetch();
}
getdata();

This will instruct the widget to fetch whatever file is waiting at the above URL. You now need to display the file:

function setdata() {
datatextarea.data = feeddata;
}
setdata();

This function can be added into the existing onLoad <action> and simply creates a new URL object, sets the location attribute to the source of the feed, and then retrieves the information as the specified location. At this point, you should have something that looks a little like this:

widget_feeding.jpg

The function works; it grabs the file located at the target URL, but unfortunately, this happens to be in an XML format! This means our textarea is currently displaying the entire XML file! Another function, to traverse the XML document and pull out just the headlines, is going to be needed. Fortunately, the widget engine provides XPath 1.0 support to make extracting the required items relatively easy.

There are several steps involved in getting the data that we want; if you look at the XML document obtained by the url.fetch command, you’ll see that the news headlines we want to grab appear in an element called title, which is a child of the item element, which is a child of the channel element, which finally, is a child of the rss element. Therefore, the element we need is a great-grandchild of the root element. Remove the setData() function as we can extend the getData() function to display the headlines once they have been extracted.

Widget Walkthrough – Using loops

The Widget reference manual states that you should use a try catch loop to perform XPath functions, so you can add one to your getData() function. You will first need to obtain the XML document and place it in a variable using the parse method:

try {
doc = XMLDOM.parse(feeddata);

Next, you need to specify which elements in the XML file you want to match. This is the XPath element of your function:

titlelist = doc.evaluate( “rss/channel/item/title” );
datatextarea.data = “”;

You now need to create an array to hold the headlines as separate DOMElement objects:

titles = new Array();

In this particular rss file, there are always 19 headlines, however, if you were using a different feed, you may not know the number of headlines in advance so it is a good idea to use a for loop that operates on the length of your array:

for (n = 0; n < titlelist.length; n++) {

The DOMNodeList returned by the XPath function has a built-in property of item() which can be used to specify which DOMElement in the list you are referring to. In this case, we can match the number of the array item with the item we want to store in the array:

titles[n] = titlelist.item(n);

Finally, each time the loop iterates, you can set the data property of the <textarea> to the data held in the array item. The actual item held in the array is the DOMElement; to get the actual text held in the object you need to address the firstChild of the element. The JavaScript new line character is also specified (twice) to break up the headlines:

datatextarea.data += titles[n].firstChild.data + “nn”;
}
}
catch(e) {
print(e);
}

Widget Walkthrough – Fine tuning headline retrieval

If you save the changes and reload the file now, the headlines should appear as if by magic! Using the <textarea> is good because it makes setting the preferences easy and handles the word wrapping well. One major flaw of this though is that it’s not possible to set the URL of each individual headline. To compensate for this, you can add a right-click menu item to the widget that takes you to either the main news front page, or a page containing the list of headlines displayed. To do this, you can add the following code block to the <textarea> element:

<contextMenuItems>
<menuItem title=”Open BBC Technology News”>
<onSelect>openURL
(”http://news.bbc.co.uk/1/hi/technology/default.stm”);</onSelect>
</menuItem>
<menuItem title=”Open the actual headlines page”>
<onSelect>openURL
(http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml);
</onSelect>
</menuitem>
</contextMenuItems>

This at least provides you with a way of reading the full news stories. Another thing that you need to consider is a way of updating the file used as the source of the data; if the computer and widget are left running, the reader will just display the same data, forever. A timer element can be used to specify that an action could be carried out repeatedly on a set interval:

<timer>
<interval>10</interval>
<onTimerFired>getdata();</onTimerFired>
</timer>

The interval is measured in seconds, but this kind of widget wouldn’t really need to grab a new rss file every ten seconds. Depending on the frequency of updates at the source, you could probably set it to update maybe several times daily.

widget_finished.jpg

Widget Walkthrough – Publishing your widget

In order to get your widget published on the Yahoo! Widget Gallery, you need to switch off debugging and package your widget. Right at the top of the file, you’ll find the <debug> element; set this to off. To package the application and produce the flat, one-file version of the existing files and folder structure, you’ll need to get to grips with the command line interface (CLI) included in the SDK. The converter is situated (on a Windows XP system) at the following location:

C:Program FilesYahoo!Yahoo! Widget Engine

You need to create an output directory at this stage so create a folder, also at the above location, called feeder or something similar. Now open a command prompt. It will probably open (on a Windows XP system) in your My Document folder so you’ll need to use the cd (change directory) command to browse to the location of the CLI. You should also move your widget folder into the same directory as the CLI and output directory. Once this has been done, use the following command to package your creation:

converter_4a convert -v -flat TechFeeder.widget -o outputDirName

You should then end up with a flat file package containing all of the files that make up the widget in the output folder. Your widget should now be ready to go onto the gallery, but don’t submit this one (because I already have).

The tagline displayed on the home page of the Widget gallery is “The grass is greener on both sides” which pays homage to widgets’ cross platform compatibility. When creating widgets, you should ensure that you test your widget on a Mac and that it runs on both Mac and Windows platforms. I have tested this widget on a Mac and unfortunately, it doesn’t work as well as it does on Windows systems; instead, it just displays the first headline. I don’t actually know why this is, but I am investigating. In the meantime however, I’ve specified on the gallery that it’s Windows only. Also, the Widget optimizer tool is supposed to be used to remove unnecessary memory forks on widget created on the Mac, but like the converter tool it isn’t currently available, so for the time being, those of you on Macs I guess will have to forgo this at present.

There is a lot more that could be done to refine the widget. At this stage it really is just a version 1.0 release. You could add a function that automatically scrolls the headlines perhaps, or create the headlines as individual text elements, each with their own URL property to make them clickable links to each of the news stories, or even include the description in a title element that displays when the mouse runs over each text element; the possibilities are endless. But what you have now is a very basic, but fully functional widget, produced with ease and in not much time at all. This is the beauty of the Yahoo! Widget Engine, speed and ease of deployment and fully functional information management right on your desktop.

Displaying ADO Retrieved Data with XML Islands

(No Ratings Yet)
Loading ... Loading ...

An XML data island is a piece of well-formed XML embedded into an HTML file. This article will show you how to retrieve data in an XML format from a database using ADO; you will also learn how to bind this data into an HTML document.Introduction

The previous tutorial, The Why and How of XML Data Islands, considered embedding a well formed XML fragment into an HTML file to create an XML data island. The article also showed how one could access data embedded in the XML file. The tutorial also described data binding to various HTML tags. However the XML data used was a hard-coded XML fragment.

In this tutorial, how data in XML format can be retrieved from a database using ADO will be described. The XML data obtained using ADO will be reviewed. An example of how Jet Data types are associated with XML data types will be shown. This will be followed by how to use the data to bind it to an HTML document. After all, this is what the client is after. It will be helpful if the reader reviews the previous article and the XML related articles to which you can find links on this site.

Data to XML Conversion using ADO

Persisting data in the XML format is one of the most important features of ADO since the 2.5 version. This means that ADO recordsets can be saved as an XML file to a location of your choice. Alternatively they can also be saved to a Stream object. Since the data is derived from a database together with the data, the data structure comes with it. Ideally this format should be able to be transparently used by any machine.

Displaying ADO Retrieved Data with XML Islands – Extracting XML formatted data example

Using the save() method of ADO, you could save the recordset to a file as shown in the next paragraph. The recordset is created by accessing an MDB file on the hard drive. Not all the columns in the ‘Employees‘ table in the Northwind database will be saved as an XML file. The variable fileName points to the location on the hard drive where the XML file will be saved.

adoxml011.jpg

Create UI to test code

On a form in your MS Access application add a button, and to the click event of this button add the following code. The statement

rs.save fileName, adPersistXML >

can also be saved as

rs.save fileName2, adPersistADTG

where fileName2 will have an .adtg extension. This is yet another proprietary format called the Advanced Data TableGram format. We will only look at the persisted XML formatted file.

Private Sub Command0_Click()
Dim rs As New ADODB.Recordset
fileName = "C:NwindEmployees.xml"
rs.Open "Select * from Employees where LastName='Peacock'", _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:Documents and SettingsJayMy DocumentsRetrieve.mdb;" & _
"Persist Security Info=False", adOpenKeyset, adLockOptimistic,
adCmdText
If Dir$(fileName) <> "" Then Kill fileName
rs.Save fileName, adPersistXML
End Sub

In the above code the recordset for the indicated SQL statement will be saved.

Displaying ADO Retrieved Data with XML Islands – The Saved XML file

If you open the file C:NwindEmployees.xml in a text editor you can see the full details.

<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
        xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
        xmlns:rs='urn:schemas-microsoft-com:rowset'
        xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
        <s:ElementType name='row' content='eltOnly' rs:updatable='true'>
               <s:AttributeType name='Address' rs:number='8'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Address'>
                       <s:datatype dt:type='string' dt:maxLength='60'/>
               </s:AttributeType>
               <s:AttributeType name='BirthDate' rs:number='6'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='BirthDate'>
                       <s:datatype dt:type='DateTime'rs:dbtype='variantdate' dt:maxLength='16' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='City' rs:number='9'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='City'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='Country' rs:number='12'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Country'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='EmployeeID' rs:number='1'rs:maydefer='true' rs:writeunknown='true' rs:basetable='Employees'
                        rs:basecolumn='EmployeeID'rs:autoincrement='true'>
                       <s:datatype dt:type='int' dt:maxLength='4'rs:precision='10' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='Extension' rs:number='14'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Extension'>
                       <s:datatype dt:type='string' dt:maxLength='4'/>
               </s:AttributeType>
               <s:AttributeType name='FirstName' rs:number='3'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='FirstName'>
                       <s:datatype dt:type='string' dt:maxLength='10'/>
               </s:AttributeType>
               <s:AttributeType name='HireDate' rs:number='7'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='HireDate'>
                       <s:datatype dt:type='dateTime'rs:dbtype='variantdate' dt:maxLength='16' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='HomePhone' rs:number='13'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='HomePhone'>
                       <s:datatype dt:type='string' dt:maxLength='24'/>
               </s:AttributeType>
               <s:AttributeType name='LastName' rs:number='2'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='LastName'>
                       <s:datatype dt:type='string' dt:maxLength='20'/>
               </s:AttributeType>
               <s:AttributeType name='Notes' rs:number='16'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Notes'>
                       <s:datatype dt:type='string'dt:maxLength='536870910' rs:long='true'/>
               </s:AttributeType>
               <s:AttributeType name='Photo' rs:number='15'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Photo'>
                       <s:datatype dt:type='string' dt:maxLength='255'/>
               </s:AttributeType>
               <s:AttributeType name='PostalCode' rs:number='11'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='PostalCode'>
                       <s:datatype dt:type='string' dt:maxLength='10'/>
               </s:AttributeType>
               <s:AttributeType name='Region' rs:number='10'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Region'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='ReportsTo' rs:number='17'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='ReportsTo'>
                       <s:datatype dt:type='int' dt:maxLength='4'rs:precision='10' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='Title' rs:number='4'rs:nullable='true' rs:maydefer='true' rs:write='true'rs:basetable='Employees'
                        rs:basecolumn='Title'>
                       <s:datatype dt:type='string' dt:maxLength='30'/>
               </s:AttributeType>
               <s:AttributeType name='TitleOfCourtesy'rs:number='5' rs:nullable='true' rs:maydefer='true' rs:write='true'
                        rs:basetable='Employees'rs:basecolumn='TitleOfCourtesy'>
                       <s:datatype dt:type='string' dt:maxLength='25'/>
               </s:AttributeType>
               <s:extends type='rs:rowbase'/>
        </s:ElementType>
</s:Schema>
<rs:data>
        <z:row Address='4110 Old Redmond Rd.'BirthDate='1958-09-19T00:00:00' City='Redmond' Country='USA'EmployeeID='4'
                Extension='5176' FirstName='Margaret'HireDate='1993-05-03T00:00:00' HomePhone='(206) 555-8122'LastName='Peacock'
                Notes='Margaret holds a BA in English literature fromConcordia College and an MA from the American Institute of Culinary Arts.She was temporarily assigned to the London office before returning to her

permanent post in Seattle.'
                Photo='EmpID4.bmp' PostalCode='98052' Region='WA'ReportsTo='2' Title='Sales Representative' TitleOfCourtesy='Mrs.'/>
</rs:data>
</xml>

Displaying ADO Retrieved Data with XML Islands – Reviewing the saved file

Although the file is large, it consists basically of two parts, as shown in the browser display of this file after collapsing all the details. As seen in the next picture, the file’s two parts are the ‘Schema’ and the ‘Data’ represented by their prefixes, ‘s:‘ and ‘rs:‘ as shown in the namespaces — the first four lines in the document which have the prefix xmlns.

adoxml021.jpg

The schema section

The next picture shows just one element from the expanded ‘s‘ node in the displayed XML file in the browser. You can also see that it is updatable. This particular slice corresponds to the ‘Address‘ field of the Employees table shown in the first picture. The fields are listed alphabetically in the persisted file. The other elements also show the various attributes of the Address field. In the original table, the Address field’s Data type is text and field size is 60. The XML attribute with the prefix ‘dt’ which marks the beginning of each row shows this information. The ‘text’ has become ’string’ and the field size has become ‘maxlength.’ The schema information therefore is an accurate representation of the data structure.

The Data Section

The next section shows the only row of data taken from the data section. The prefix ‘z’ marks the beginning of the data. The XML file has only one row of the table returned corresponding to the LastName=’Peacock.

peacock1.jpg

Displaying ADO Retrieved Data with XML Islands – Data types in Access 2003 and XML file

In MS Access there are several data types that are typical to its Jet Library. In order to look at how the data goes over into XML, a table, called ‘Whimsical‘ was contrived which has all the data types but contains only a single row of data. This was opened just like the previous table and the saved file was examined. In the next picture you see the table and in the one that follows, you see the ’schema’ section. The data types, ‘bitmap’, and ‘hyperlink’ can take up a large amount of space. This one row of data saved to file takes up as much as 0.5 MB.

adoxml061.jpg

This is the ‘Schema’ section of the above file. Review each of the data types and you’ll see the corresponding dt:type in the XML file.

adoxml051.jpg

Displaying ADO Retrieved Data with XML Islands – Displaying retrieved XML in an HTML document

Creating an XML Data Island

From the previous tutorial we know that we need to embed the XML in an XML document to produce the XML Data Island. The ADO’s save() method does not produce a data island. This can be built in two steps. First of all, to associate the ‘Data’ contained in the XML to the bondable tags of the HTML, we need a basis of association. This is given by the following XML block with the id=’test.’

<XML id="test">


</XML>

In the second step, you will notice that XML is already the first tag in the saved file. Since you cannot have two XML tags, you modify the saved file by prefixing ado to xml and changing it to adoxml as shown. This will be embedded in the previous block and the resulting XML is the XML Data Island.

<adoxml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
        xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
        xmlns:rs='urn:schemas-microsoft-com:rowset'
        xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
        <s:ElementType name='row' content='eltOnly' rs:updatable='true'>
               <s:AttributeType name='Address' rs:number='8'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Address'>
                       <s:datatype dt:type='string' dt:maxLength='60'/>
               </s:AttributeType>
               <s:AttributeType name='BirthDate' rs:number='6'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='BirthDate'>
                       <s:datatype dt:type='dateTime'rs:dbtype='variantdate' dt:maxLength='16' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='City' rs:number='9'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='City'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='Country' rs:number='12'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Country'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='EmployeeID' rs:number='1'rs:maydefer='true' rs:writeunknown='true' rs:basetable='Employees'
                        rs:basecolumn='EmployeeID'rs:autoincrement='true'>
                       <s:datatype dt:type='int' dt:maxLength='4'rs:precision='10' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='Extension' rs:number='14'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Extension'>
                       <s:datatype dt:type='string' dt:maxLength='4'/>
               </s:AttributeType>
               <s:AttributeType name='FirstName' rs:number='3'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='FirstName'>
                       <s:datatype dt:type='string' dt:maxLength='10'/>
               </s:AttributeType>
               <s:AttributeType name='HireDate' rs:number='7'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='HireDate'>
                       <s:datatype dt:type='dateTime'rs:dbtype='variantdate' dt:maxLength='16' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='HomePhone' rs:number='13'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='HomePhone'>
                       <s:datatype dt:type='string' dt:maxLength='24'/>
               </s:AttributeType>
               <s:AttributeType name='LastName' rs:number='2'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='LastName'>
                       <s:datatype dt:type='string' dt:maxLength='20'/>
               </s:AttributeType>
               <s:AttributeType name='Notes' rs:number='16'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Notes'>
                       <s:datatype dt:type='string'dt:maxLength='536870910' rs:long='true'/>
               </s:AttributeType>
               <s:AttributeType name='Photo' rs:number='15'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Photo'>
                       <s:datatype dt:type='string' dt:maxLength='255'/>
               </s:AttributeType>
               <s:AttributeType name='PostalCode' rs:number='11'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='PostalCode'>
                       <s:datatype dt:type='string' dt:maxLength='10'/>
               </s:AttributeType>
               <s:AttributeType name='Region' rs:number='10'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Region'>
                       <s:datatype dt:type='string' dt:maxLength='15'/>
               </s:AttributeType>
               <s:AttributeType name='ReportsTo' rs:number='17'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='ReportsTo'>
                       <s:datatype dt:type='int' dt:maxLength='4'rs:precision='10' rs:fixedlength='true'/>
               </s:AttributeType>
               <s:AttributeType name='Title' rs:number='4'rs:nullable='true' rs:maydefer='true' rs:write='true'

rs:basetable='Employees'
                        rs:basecolumn='Title'>
                       <s:datatype dt:type='string' dt:maxLength='30'/>
               </s:AttributeType>
               <s:AttributeType name='TitleOfCourtesy' rs:number='5'rs:nullable='true' rs:maydefer='true' rs:write='true'
                        rs:basetable='Employees'rs:basecolumn='TitleOfCourtesy'>
                       <s:datatype dt:type='string' dt:maxLength='25'/>
               </s:AttributeType>
               <s:extends type='rs:rowbase'/>
        </s:ElementType>
</s:Schema>
<rs:data>
        <z:row Address='4110 Old Redmond Rd.'BirthDate='1958-09-19T00:00:00' City='Redmond' Country='USA'

EmployeeID='4'
                Extension='5176' FirstName='Margaret'HireDate='1993-05-03T00:00:00' HomePhone='(206) 555-8122'

LastName='Peacock'
                Notes='Margaret holds a BA in English literature fromConcordia College and an MA from the American Institute of Culinary Arts.

She was temporarily assigned to the London office before returning to her

permanent post in Seattle.'
                Photo='EmpID4.bmp' PostalCode='98052' Region='WA'ReportsTo='2' Title='Sales Representative' TitleOfCourtesy='Mrs.'/>
</rs:data>
</adoxml>

Displaying ADO Retrieved Data with XML Islands – Creating an HTML document which can display the XML Data

AdoIsland.html

In the code shown next, insert the XML data island created in the previous section and save it as AdoIsland.htm. Make sure the DATASRC attribute of the table corresponds to the ID field of the XML Data Island. The DATAFIELD attribute refers respectively to the data fields in the XML data island.

<html><head><title></title></head>
<body>
<table DATASRC="#Test">
<tr>
<tr><td>
<table DATAsrc="#Test" DATAFLD="rs:data" border="1"
bgcolor="yellow">
<tr><td>
<table DATAsrc="#Test" DATAFLD="z:row">
<tr>
<td><span DATAFLD="EmployeeID"></span</td>
<td><span DATAFLD="FirstName"></span</td>
<td><span DATAFLD="LastName"></span</td>
</tr>
</table>
</td></tr>
</table>
</td></tr>
</table>
<!--Here plug in the XML Data Island -->
</body>
</html>

Displaying the XML Data retrieved on the IE

Now if you browse the AdoIsland.htm file the display should appear as follows. If you refer to the table above, you can see that although all fields are in the XML Data Island, only three of them are called while displaying.

adoxml071.jpg

Displaying the image saved as an embedded BMP file

From the XML file you could retrieve the field for the ‘Photo’ and display the image on the browser. For this, you need to add another cell to the table and insert the following for the cell.

<td><img src=""  DATAFLD="Photo"></td>

With the above table cell added to the table, the display now appears as shown here. For this to display correctly you should have the corresponding BMP file at the same location as the AdoIsland.htm file.

adoxml081.jpg

Summary

This tutorial extends the previous tutorial to show how to access data and display it using the ADO’s save() method. An example to display the persisted data using the XML Data Island was described. More importantly, the data types in MS Access as they relate to data types in the persisted XML file were shown in detail. Similar ideas will help in accessing data from a web server with Active Server Pages as well.

Introduction to Widgets

(No Ratings Yet)
Loading ... Loading ...

Widget Walkthrough

A widget should be created to fill a need; it should actually do something useful. What I decided on in the end was a news reader. Every day, when I turn on my computer, one of the first things I do is to go to the BBC news website and check out the technology section headlines. I decided that my news reader would take the RSS feed supplied by the BBC and list the daily technology headlines. Thus the idea for TechFeeder was born.

The very first thing that I did was draw the main element of my widget in Photoshop (any decent graphic tool will do, but you won’t be able to use the Photoshop script if you use a different application). I won’t go into extreme detail over exactly what I did, but the tutorial I followed advised that aqua style icons are made using a layered mixture of shading, opacity and lighting effects. There are plenty of guides out there on aquifying pictures so if you’ve never created one before, I’d recommend searching for one and practicing a bit before the main event.

It took a couple of attempts before I had something that looked like I wanted it to, but soon enough I had the basic appearance that I had envisioned and settled with it. I think you’ll agree that while it isn’t perfect and has obvious flaws, it works reasonably well. Perhaps I’ll improve it for release 1.1 of my widget! While you have Photoshop open, you may as well create the image that you’ll use for the about-box for your widget. The about box should match the style of your widget if possible and list things such as the version number, author details and anything else you feel is appropriate. You can create the whole thing in Photoshop or just the background and use XML to add the text. It’s up to you, but in order to demonstrate some of the about-box capabilities, I just created the background in my image editor.

widget_background.jpg

widget_about.jpg

When you run the widget creation.jsx file, you’ll be asked to submit your name, the widget version and choose a location for the widget directory to be created. Once it has finished, you’ll need to go into the contents folder and open the .kon file in a text editor.

You should be presented with some code that looks very similar to this:

<?xml version=”1.0″ encoding=”UTF-8″?>
<widget version=”1.0″ minimumVersion=”2.0″ author=”Dan Wellman”>
<debug>on</debug>
<window title=”TechFeeder”>
<name>mainWindow</name>
<width>206</width>
<height>141</height>
<visible>1</visible>
<shadow>0</shadow>
</window>
<image src=”Resources/Shape 1.png”>
<name>Shape_1</name>
<hOffset>0</hOffset>
<vOffset>5</vOffset>
<width>206</width>
<height>136</height>
<opacity>70%</opacity>
</image>

This should make sense at first glance to anyone who’s worked with XML before. The XML declaration comes first, followed by the <widget> tag which is the container into which all other tags must be placed. Next is the <window> tag, which in this case specifies the main window. Notice that the image that makes up the main background of the widget is specified in its own <image> block, separate from (not nested within) the window element. To make the widget semi-transparent, as many are, I’ve lowered the opacity of the image. I have used a percentage here, but you could also use an integer from 0 to 255 to specify the opacity.

Introduction to Widgets – Adding Your Own Code

Now you need to start adding code yourself. What I focused on first was the about-box, which is an element used solely to display a little window listing the program version, the creator, and anything else as a programmer that you want or need to display. As I’m using content from the BBC site, I felt it necessary to include their copyright information:

<about-box>
<image>Resources/about-backg.png</image>

<about-version>
<font>Arial</font>
<size>12</size>
<style>bold</style>
<hOffset>90</hOffset>
<vOffset>45</vOffset>
<color>#ffffff</color>
</about-version>
<about-text>
<data>BBC TechFeeder</data>
<font>Arial</font>
<size>18</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>30</vOffset>
</about-text>

<about-text>
<data>Copyright:(C)</data>
<font>Arial</font>
<size>12</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>90</vOffset>
</about-text>
<about-text>
<data>British Broadcasting Corporation</data>
<font>Arial</font>
<size>10</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>105</vOffset>
</about-text>
<about-text>
<data>Click here for terms and conditions</data>
<url>http://news.bbc.co.uk/1/hi/help/rss/4498287.stm</url>
<font>Arial</font>
<size>10</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>120</vOffset>
</about-text>
<about-text>
<data>of reuse.</data>
<font>Arial</font>
<size>10</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>130</vOffset>
</about-text>

<about-text>
<data>By Dan Wellman</data>
<font>Arial</font>
<size>14</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>185</vOffset>
</about-text>
<about-text>
<data>2006</data>
<font>Arial</font>
<size>12</size>
<style>bold</style>
<color>#ffffff</color>
<hOffset>90</hOffset>
<vOffset>200</vOffset>
</about-text>
</about-box>

It’s a whopping amount of code for one small window, most of which is graphic, but it’s easy code and should make absolute sense at a glance. The about-version code actually pulls the version number from the main kon file at run time. The reason it’s so large is that at present, text in the about-box doesn’t wrap and is simply cut off at the end of the window. This is why there are so many <about-text> blocks; each line is its own separate object. The <about-version> and <about-text> blocks are listed separately, much like the <image> element above. Note that the about box must feature an image in order to function and that the bit of the text that is a hyperlink must have the <url> attribute set in the relevant code block. Once complete, the about box will appear like this:

widget_about2.jpg

Introduction to Widgets – Displaying Data

The application will be getting information from a news feed and it is going to need to display the information somewhere in order to carry out its function. I’ve created a text area to display the data for its multi-line facility, and I’ve enclosed it in a frame element primarily because of the automatic scrollbar capabilities that this element features:

<frame name=”dataframe”>
<textarea name=”datatextarea”>
<data>Loading…</data>
<font>Arial</font>
<editable>false</editable>
<color>#000000</color>
<size>12</size>
<style>bold</style>
<height>80</height>
<width>150</width>
<voffset>35</voffset>
<hoffset>30</hoffset>
<bgcolor>#cccccc</bgcolor>
<bgopacity>0</bgopacity>
</textarea>
</frame>

If you set the data element to hold the text “Loading…” this is what will be displayed when the widget first appears on screen. This is important because it takes a few seconds before the data is pulled through and parsed from the RSS feed. You’ll see in one of the functions later on that the data property of the text area is loaded after the source file has been obtained.

It’s great that the scroll bar handles, track and face are all drawn for you with absolutely no additional coding when using a frame element. You can also specify a frame element that will override this automaton and can be controlled via script. Doing this is a bit beyond the scope of this article, but such an element could be used as part of a function that automatically scrolls the text displayed in the text area.

Introduction to Widgets – Setting the Preferences

Next, I tackled the preferences. The widget engine will draw the preferences box for you and include the common options such as locking the widget’s position and setting the opacity. All you have to do is specify any additional options, and write the JavaScript to make them work:

<preference>
<name>textfontpref</name>
<defaultValue>Arial</defaultValue>
<title>Text Font:</title>
<type>font</type>
<description>Select a font for the news text.</description>
</preference>

<preference>
<name>textcolorpref</name>
<defaultvalue>#000000</defaultvalue>
<title>Text Color:</title>
<type>color</type>
<defaultValue>#000000</defaultValue>
<description>Select a colour for the news text.</description>
</preference>
<preference>
<name>textsizepref</name>
<defaultvalue>12</defaultvalue>
<title>Text Size:</title>
<type>popup</type>
<option>8</option>
<option>10</option>
<option>12</option>
<option>14</option>
<description>Select a font size for the news text.</description>
</preference>

<preference>
<name>textstylepref</name>
<defaultvalue>Bold</defaultvalue>
<title>Text Color:</title>
<type>popup</type>
<option>Bold</option>
<option>Italic</option>
<option>Narrow</option>
<option>Expanded</option>
<option>Condensed</option>
<option>Smallcap</option>
<option>Poster</option>
<option>Compressed</option>
<option>Fixed</option>
<option>No Style</option>
<description>Select a text style for the news text (it will only be applied if
supported by the font).</description>
</preference>

Widgets should be as customizable as possible; therefore, I’ve given the user control over everything that isn’t an image, which in this case is just the text from the BBC news feed. Each property you are able to change has its own segment of code. The <type> attributes of the first two preferences are used by the engine to automatically create a font chooser that previews all of your installed fonts, and a color picker, as seen in other applications.

In part two of this article I’ll show you how to wire up these preferences with a little bit of script to actually make them work. We’ll also work on the main script that makes the whole thing tick, and look at packaging and preparing the widget for upload to the online gallery.

By Dan Wellman

Roaming Through XMLDOM: An AJAX Prerequisite

(1 votes, average: 5.00 out of 5)
Loading ... Loading ...

The twin tasks of the XMLHttp are handling the HTTP request, and then processing the XML response. The first one is easily done by writing the appropriate syntax for creating this object. This is what is accomplished in AJAX by invoking the new constructor for XMLHTTP object. This is but one of the objects of the XMLDOM -XML Document Object Model. In this article, we look at XMLDOM in some detail before calling the XML document in an AJAX rendition in a future article.

A quick look at XMLDOM

The DOM of HTML and XMLDOM share some common traits. The basic precept that documents are hierarchically structured with nodes and nested nodes is common to both of them. The DOM object model as seen in W3C documentation is described in full here.

XMLDOM can be understood through two types of metaphors, a tree representation and a family representation. In the tree representation, the tree has nodes. Nodes can have other nodes growing out of them, or a node can stand by itself without any other nodes sprouting from it. In the family metaphor you have parents, children, siblings, and so on.

Accessing XML via XMLDOM is facilitated by ActiveX. All that is needed is to create a new ActiveXObject, via the call:

var xml_doc=new ActiveXObject (”Microsoft.XMLDOM”);

Once this is created, an XML document from a given location can be loaded. Then we can look at the various properties of this object as detailed in the XMLDOM. The following listing gives a brief description of the XMLDOM objects that are well suited for client side scripting.

In XMLDOM as well as HTML’s DOM the following interfaces are used for accessing. In the present tutorial we will only look at a subset of the properties and methods of the highlighted objects.

  • Attr
  • CharacterData
  • Comment
  • DocumentFragment
  • Document
  • DOMException
  • DOMImplementation
  • Element
  • Node
  • NodeList
  • NamedNodeMap
  • Text

Document

Document is the root of the XML document.

ElementThe element object represents the Document’s various elements, such as root and other elements.

Node“Node” is a single node in the document tree representation. This has support for data types, namespaces, DTDs and XML Schemas.

Attribute“Attribute” represents the single attribute node of an element.

Text“Text” represents the text of an element or attribute.

Roaming through XMLDOM: An AJAX Prerequisite – Getting at the Innards of an XML Document

We will briefly look at some of the XML Dom objects. In order to show how the code accesses the various parts of a document, consider the following well formed XML document WebClass.xml which is located on my hard drive at:

C:/Documents and settings/computer user/Desktop/todo/Ajax/WebClass.xml.

XML document probed

<?xml version="1.0" encoding="ISO-8859-1" ?><wclass>

<!-- My students who attended my web programming class -->

<student id="1">

<name>Linda Jones</name>

<legacySkill>Access, VB5.0</legacySkill>

</student>

<student id="2">

<name>Adam Davidson</name>

<legacySkill>Cobol, MainFrame</legacySkill>

</student>

<student id="3">

<name>Charles Boyer</name>

<legacySkill>HTML, Photoshop</legacySkill>

</student>

<student id="4">

<name>Charles Mann</name>

<legacySkill>Cobol, MainFrame</legacySkill>

</student>

</wclass>

Slicing the XML document

First things first: we need to instantiate an XMLDocument object. This is done easily by running the following code as shown:

<SCRIPT LANGUAGE="JavaScript">var xml_doc = new ActiveXObject("Microsoft.XMLDOM");

xml_doc.async = false;

xml_doc.load ("C:/Documents and settings/computer user/Desktop/todo/Ajax/WebClass.xml");

</SCRIPT>

After this step we will look at a number of properities that can be accessed using code.

First Child and Last Child Properties

These properties can be accessed if you insert the following lines after loading the document as shown above but before </Script>,

document.write ("This documents first child is a " +xml_doc.documentElement.firstChild.nodeName);

document.write("<br>");

document.write ("This document's  last child= " +

xml_doc.documentElement.lastChild.nodeName);

and if you display it in a browser you would see the following:

This documents first child is a #commentThis document's last child= student

Roaming through XMLDOM: An AJAX Prerequisite – Continuing the Dissection
Document Element Properties

The Document element has a child nodes collection you can access by iterating through the index. You can also access the attributes, which consist of a name and a value as shown here. The following code should be inserted after creating the XMLDOC object.

document.write("<br>"+xdoc.documentElement.childNodes.item(0).text +"<br>");document.write("<br>"+xdoc.documentElement.childNodes.item(1).

attributes[0].name +"<br>");

document.write("<br>"+xdoc.documentElement.childNodes.item(1).

attributes[0].value +"<br>");

When the above snippet is run you would see the following.

My students who took web programming class with meid

1

Nodes Collection

In the document we are looking at, we have a number of student nodes. We can get a reference to the student nodes using the getElementsByTagName method. From this we can find the number of such student nodes. Once we know how many there are (nodes.length), we can iterate through the collection and find the individuals as shown in the following code.

var nodes=xdoc.getElementsByTagName("student");document.write("<br>Number of student nodes is "+nodes.length+"<br>");

for (i=0; i< nodes.length; i++)

{document.write("<br>"+nodes.item(i).text+"<br>");}

If you were to include the code in the script after instantiating the xdoc object you would see the following:

Number of student nodes is 4Linda Jones Access, VB5.0

Adam Davidson Cobol, MainFrame

Charles Boyer HTML, Photoshop

Charles Mann Cobol, MainFrame
Node’s name, type and value

Once you locate an element’s child node through its collection, as in the declaration of Elem in the next snippet, you could determine its name, type and value by calling respectively the nodeName, nodeType and nodeValue properties as shown.

var Elem=xdoc.documentElement.childNodes.item(2);document.write("<br>"+Elem.nodeName+"<br>");

document.write("<br>"+Elem.nodeType+"<br>");

document.write("<br>"+Elem.nodeValue+"<br>");

We have located the second child and its properties by running the above script as shown.

student1

null
Family metaphor related items

As mentioned earlier, in addition to the tree representation (tree metaphor) there is also the family representation (somewhat seniority based). These are usually parent, sibling, previous sibling, next sibling, and so on. The next few lines of code will give you an idea how we may access them. We will be starting with the second student whose id=2.

//second student is referenced.var midElem = xdoc.documentElement.childNodes.item(2);

document.write("<br>"+midElem.attributes[0].value+"<br>");

document.write("<br>"+midElem.previousSibling.text+"<br>");

document.write("<br>"+midElem.nextSibling.text+"<br>");

document.write("<br>"+midElem.parentNode.nodeName+"<br>");

document.write("<br>"+midElem.parentNode.nodeType+"<br>");

document.write("<br>"+midElem.parentNode.nodeValue+"<br>");

When the above code is inserted after instantiating xdoc as described previously, you would see the following displayed.

2Linda Jones Access, VB5.0

Charles Boyer HTML, Photoshop

wclass

1

null

Roaming through XMLDOM: An AJAX Prerequisite – Manipulating the XML Document
(Page 4 of 4 )

The XMLDOC object also has a large number of methods that can be invoked to create, modify, and delete nodes. The document object represents the XML file in its entirety and is also a node in the DOM. It has a large number of properties and many methods. For complete documentation the reader is referred to the W3C site. In addition to W3C there are also Microsoft extensions.

Adding a new student to the web class

Being a node, XMLDOC shares the properties of the nodes as well. A complete usage of the methods is not attempted, but a few examples are shown as related to the XML document we have been considering, the WebClass.xml file. XMLDOC object’s methods will be invoked to add another student to the web class file. This is what a student node looks like. We will add another student according to this scheme.

<student id="1">  <name>Linda Jones</name><legacySkill>Access, VB5.0</legacySkill>

</student>

Looking at the node, student, we see that in order to add a new student node we need to add the name and legacySkill child nodes. Also we need to add the attribute Id and give a value to it. Finally we need to add the proper texts for the name and legacySkill nodes.

We assume that the new student will have:

id –> 7
name–>John Doe
legacySkill–>Fortran, Soroban
The code for adding the new student is as follows:

//This creates a new student:
var newElem= xdoc.createElement(”student”);

//This line creates the attribute to the new student:
var newAtt=newElem.setAttribute(”id”,7);

//The next two lines creates elements name and legacySkill
var part1=xdoc.createElement(”name”);
var part2=xdoc.createElement(”legacyskill”);

//The next two lines create the required text for the nodes:
var newText1=xdoc.createTextNode(”John Doe “);
var newText2=xdoc.createTextNode(”Fortran, Soroban”);

//Appending the name and legacySkill to the student node
var part11=newElem.appendChild(part1);
var part21=newElem.appendChild(part2);

//Adding the text content to the name and legacySkill nodes
part11.appendChild(newText1);

part21.appendChild(newText2);

In this fashion you build the tree so that the node is defined according to the blueprint from the XML document. This completes the building of the student node.

Verifying the new student information

In order to verify, we again invoke the XMLDOC’s properties as shown in the early part of this tutorial. In particular we will be using the following code to verify:

//We created newElem and the node’s name is given by: document.write(newElem.nodeName);

//We get the following result for this line:
student

//We have not added the newElem to xdoc and presently the number of //nodes in xdoc are given by:
var totalnodes=xdoc.getElementsByTagName(”student”);
document.write(”<br>”+totalnodes.length);

//the result of this code gives the number of student nodes in xdoc:
4

//We look at the attributes of the new student node:
document.write(”<br>”+ newElem.attributes[0].name);
document.write(”<br>”+ newElem.attributes[0].value);

//We get the following result for the above code snippet:
id
7

//We now grab the text for the entire student node:
document.write(”<br>”+newElem.text);

//This snippet gives the following browser display:
John Doe Fortran, Soroban

//Now we get a reference to the last child of the xdoc before adding the //new student:
var lastnode=xdoc.lastChild;

//This is important. We add the newElem student node to the xdoc:
lastnode.appendChild(newElem);

//We now count the number of nodes in the new document which have //the student nodes:
var totalnodes=xdoc.getElementsByTagName(”student”);
document.write(”<br>”+totalnodes.length);

//The result of this in the browser display is:
5

This verifies that the new student has been added (we started out with 4). The file can be saved using the save (ObjTarget) method of the XMLDOC object.

Summary

Understanding and manipulating the XMLDOM objects is a prerequisite to writing successful code, whether it be for AJAX or for anything to do with XML files especially using Microsoft tools. It is the author’s hope that the surgical presentation of this tutorial in dissecting the XMLDOM object will provide a guide to this understanding. XMLHTTP request is another object belonging to the XMLDOM; it is discussed in a previous tutorial and will be revisited again in discussing the responseXML method of the request object.

Step by Step to AJAX

(No Ratings Yet)
Loading ... Loading ...

AJAX has been exciting many programmers as the latest and greatest thing in web development. This article takes a step-by-step look at the Microsoft way to script for AJAX.

Introduction This tutorial is not about Ajax Telamon from the Iliad who fought Hercules, but the latest and greatest (at least in the opinion of some) thing in web development. Ever since Google charmed the web at large with those AJAX-created Google Maps apps, the number of amount of adherence to AJAX has been growing exponentially. In this tutorial, we look mainly at the Microsoft way of scripting for AJAX. Like my previous tutorials, it’s step by step all the way after a brief introduction.

Web Application EvolutionSince 1992 developers have relentlessly pursued ways to make the web more appealing, more productive and more interactive. The plain text html at birth soon saw embedded images followed by appealing colors conferred by cascading style sheets. But it was left for JavaScript to bring user interaction, and thus began the heydays of scripting languages.

However, there were two major browsers sharing the web space, and two scripts to serve the user (the third, ECMA came later). This was not enough, and DHTML was born – not a new language, but a good mix of html, CSS, and JavaScript that made user interaction extremely satisfying.

AJAX came along to make the interaction more responsive without needing to refresh the page. AJAX is an acronym, and the credit for coining this name goes to Adaptive Path’s S. S. Garret. However, Microsoft appears to be the progenitor, with its flagship ActiveX Technology making this possible. Now it is a mélange of XHTML, CSS, JavaScript, XmlHttpRequest, and XML, and its DHTML déjà vu all over.

Step by Step to AJAX – Ajax’s Model of Interaction

The figure shown next is derived from Garret’s article on Ajax, redrawn to render it horizontally. The figure shows both the prior art (classic interaction) as well as the AJAX embodiment. In the classic version, the client sends an HTTP(S) request to the server, the server checks to see whether any server side processing is to be carried out, processes the server related instructions and sends back the html with CSS, if it is defined. There is a synchronicity between client request and server response.

In the AJAX model, the client sends a JavaScript to AJAX, and AJAX sends the HTTP(S) request to the web server which can also serve XML. The web/XML server sends back the result in the form of XML, and AJAX relies on the Document Object Model (DOM: blue print of web document) to transmit the result in XHTML and CSS. It does so by reading the returned XML’s node tree using DOM. The interaction could be synchronous or asynchronous.

AJAX

Step by Step to AJAX – XmlHttpRequest

One of the key objects needed for working with AJAX is the XMLHttpRequest Object. This object does two things: it handles the httpRequest, and then it processes the XML response. This was implemented in Internet Explorer 5 for Windows as an ActiveX Object. This has been implemented by Mozilla 1.0, Apple and others in compatible forms. The W3C has similar standards for the DOM Level 3 specification. We will take a brief look at this object before we put it to work. Some of the highlighted methods and properties are later used while fetching a web page to show what values they do return.

Creating the XML HttpRequest objectThis is the easy part, if you need to deal only with Microsoft IE. For Mozilla you would instantiate the object using the following syntax:

var xhr=new XMLHttpRequest();

where as for IE you would use the following:

var xhr=new ActiveXObject(”Microsoft.XMLHTTP”);

Both of these methods create an object which is hidden from the user. Its methods and properties take control of the server interaction. For cross browser applications you need to come up with a branching syntax. This is not so difficult; see for example the cross-browser boiler plate code (Listing 2.0 in the link).

Step by Step to AJAX – XMLHttpRequest Object Methods

This short list of methods is shared by all supported browsers. In this tutorial we shall look at some of the highlighted methods.

abort()
current request is stopped
getAllResponseHeaders()
returns a string containing information of headers
getResponseHeader (”headerlabel”)
returns a string containing information about a single header
open(”method”, “URL”[,asyncFlag[,"userName"[,"password"]]])
assigns various request attributes
send(content)
Transmits the data with information that may be posted, if needed
setRequestHeader (”label”, “value”)
assigns label, value pair for the header

While open() and send() are most often used, the others are also useful in some cases. The open() method begins the interaction and takes two mandatory arguments; the “method” used to open, which is either GET or POST, and the URL to which the request is made.

The GET and POST methods are similar to those used in ASP, as some of you might recognize. The GET is indicated for retrieving read only data while POST is for sending data to the server.

The URL could be complete, or a relative URL.

The third parameter which is optional (default value TRUE being asynchronous) sets the interaction to be synchronous (FALSE) or asynchronous (TRUE). If you choose the synchronous route, the script waits for the response to arrive before acting. The useful mode is to set the interaction to be asynchronous and use the onreadystatechange event (to be discussed) to get at the response.

XMLHttpRequest Object PropertiesThe following read only properties are browser agnostic (all supported browsers understand them).

onreadystatechange
Event handler which fires every time the state changes
readState
Integer representing the status of the object
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText
Data returned in string format
responseXML
Data returned in DOM Compatible format
status
Numeric code returned by server indicating status
404: Not found
200: OK
statusText
Message string that came with the status

Step by Step to AJAX – Fetching a page using AJAX

Working with AJAX is quite simple. The code will be explained by explaining the component parts with reference to an html file, AjaxTest.htm. First you need to create an XMLHttpRequest Object along the lines discussed above. Then you make a request, in this case pass an URL as an argument to the getPage() function. Since you are getting back a page you just need to use the GET argument. Since an asynchronous interaction is intended, use TRUE for the third argument in the open() method.

Before the open() method is called the onreadystatechange eventhandler calls the statusCheck() function, where the readyState of the request is verified and the status code is verified to return OK. Both of these functions are in the <Head/> and are evaluated before the rest of the page is loaded. Review the two functions just described for the html page AjaxTest.htm. Some of the properties and methods previously described and highlighted are also returned. The script that follows this paragraph is in the <head/> section of AjaxTest.htm.

You also include code to alert you if, for some reason, the XMLHttpRequest object instantiation failed. It also needs to alert the user if the request failed because the page was unavailable, or the server was not responding, or for any other reason.

If the status is OK and the readyState shows completion, then you get the response, for this example, in the text format. Now you invoke the DOM API to get the element whose ID=”x”, in this case the <div/>, and set its innerHTML property the same as the returned text. If you look at the response produced by the alert(xhr.responseText) you would see the html of the page you requested as shown in the next picture. I particularly like the preference to use the ECMA scripting style.

<SCRIPT LANGUAGE=javascript>
<!--
var xhr = false;
function getPage (url) {
xhr = false;
//this is the Microsoft browser compatible instantiation
xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) {
alert ('XMLHttpRequest failed to instantiate');
return false;
}
xhr.onreadystatechange = statusCheck;
xhr.open ('GET', url, true);
xhr.send (null);
}
function statusCheck() {
txt1.value="XmlHttpRequest_Status: " + xhr.status;
txt2.value="XmlHttpRequest_readyState: " + xhr.readyState;
TEXTAREA1.value="XmlHttpRequest_getallResponseHeaders(): " +
xhr.getAllResponseHeaders();
txt5.value="XmlHttpRequest_statusText: " + xhr.statusText
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText);
document.getElementById("x").innerHTML =(xhr.responseText);
} else {
alert ('There was a problem with the request.');
}
}
}
//-->
</SCRIPT>

Alert

However, when you use the DOM API, you get the following as shown:

AJAX Test

The <body/> of the AjaxTest.htm consists of just the following controls so that the properties, the methods and their values can be displayed. The onclick event starts the process rolling. Of course the <div/> is where the innerHTML property gets written. The html for these controls is as shown:

<P><STRONG><SPAN
style="FONT-SIZE: large; COLOR: red">A</SPAN>synchronous <SPAN
style="FONT-SIZE: large; COLOR: red">J</SPAN>avascript <SPAN
style="FONT-SIZE: large; COLOR: red">A</SPAN>nd <SPAN
style="FONT-SIZE: large; COLOR: red">X</SPAN>ML= <SPAN
style="FONT-SIZE: large; COLOR: blue">AJAX</SPAN></STRONG></P>
<P>
</P>
<P> </P>
<P><INPUT id=button1 type=button
onclick="getPage ('http://xphtek/TestXMLHttp/Greeting.asp')"
value="Get the page by XmlHttpRequest" name=button1></P>
<P><INPUT id=txt1 style="WIDTH: 396px; HEIGHT: 22px" size=51></P>
<P><INPUT id=txt2 style="WIDTH: 395px; HEIGHT: 22px" size=50></P>
<P><TEXTAREA id=TEXTAREA1 style="WIDTH: 393px; HEIGHT: 72px"
name=TEXTAREA1 cols=42></TEXTAREA></P>
<P><INPUT id=txt5 style="WIDTH: 389px; HEIGHT: 22px"
size=50></P>
<div id="x"></div>

As previously mentioned you can reference the URL completely, as in http://xphtek/TestXMLHttp/Greeting.asp or simply by its relative URL Greeting.asp. The Greeting.asp page is a simple page as shown:

 <%@ Language=VBScript %>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<script language="javascript">
document.write (document.lastModified);
</script>
</HEAD>
<BODY>
<%Response.Write("<b>Welcome to programming with AJAX</b>")%><br>
<% =Date()%><br>
Hello<br>

</BODY>
</HTML>

Summary The tutorial has looked at the various properties and methods of this interesting XMLHttpRequest object. It goes without saying that the browser should support JavaScript, and as a developer you should appropriately warn the user to enable JavaScript, if it is not. For Microsoft IE there is the additional requirement of browser support for ActiveX objects.

For recent browsers the older method of using iframes to update parts of a page will be replaced. However iframes may still find favor with much older browsers. In this tutorial we saw most of the properties, but the lastmodified property returned null; the syntax was double checked but to no avail. Although AjaxTest.htm was coded on Visual Interdev 6.0, it is not a requirement; plain Notepad should work as well.