Internet Explorer 8 web slices

I don't understand if we have to consider this feature as a new attempt to resume the old browser war era or simply a response to the viral spread of the RSS standard. I'm inclined to think it in the first way, because Internet Explorer is actually losing its battle against Firefox and Chrome. Well, we'll see. In the meantime, watch this video from Microsoft.

Parsing XHTML with PHP SimpleXML

Again, XHTML is really powerful when served as application/xhtml+xml. We can even parse it with the PHP SimpleXML library. For example, given the following markup:

<body>
  <p>Test</p>
</body>

we can write the following PHP code:

$xhtml_file = 'test.xhtml';
$xhtml_doc = simplexml_load_file($xhtml_file);

$p = $xhtml_doc->body->p;
echo $p; // 'Test'

Very simple, isn't it? The fact is that XHTML is treated exactly as XML when served with its proper content type.

Parsing XHTML with the PHP DOM extension

When served as application/xhtml+xml, XHTML is simply treated as XML so we can parse an XHTML document as if it was an XML file. Here's how it can be done using the PHP DOM extension: given the following XHTML fragment

<div id="test">
  <p>Test</p>
</div>

we can use the following PHP code:

$document = new DOMDocument();
$document->load('test.xhtml');

$test = $document->getElementById('test');
$p = $test->getElementsByTagName('p')->item(0)->firstChild->nodeValue;

echo $p; // 'Test'

Obviously we can parse this way even more complex XHTML documents, because the DOM extension allows us to access every single node within an XHTML document.

Overuse of web icons considered harmful

Web icons should be used carefully due to the amount of cognitive load that they generate for users. In fact, an icon is something that users have to decode to properly understand their meaning and semantics. What happens when an icon is polysemic? For example, what does a star mean? Favorites, bookmarks, ratings, or what?

The point is: without a proper explicative text used together with icons, the overuse of web icons may be harmful for users. This is both an accessibility and usability issue. Either people with cognitive disabilities or normal users may encounter problems when dealing with icons. Decoding an icon is something that is often difficult, because you have to think and, as many of you know, one of the most famous usability mottos claims "Don't make me think" (Steve Krug). Further, people with memory impairments may also be affected by the use of icons.

In a nutshell, icons should be used for what they really are, that is, graphics, and not as a mean to convey extra meanings. If you want to use them properly, combine them with explicative text, because what is clear and evident for you may be confusing or obscure for others.

Ajax accessibility: implementing a fallback mechanism

Ajax can be a really powerful tool if used properly. A common mistake in Ajax implementation is the lack of a fallback mechanism to be deployed when Ajax support is not present or partial. A common scenario in that sense is made up by text browsers and screen readers.

Text browsers (like Lynx) don't support Ajax at all just because they don't support JavaScript at all. Imagine a situation where you have to perform an Ajax call triggered by a onfocus event on a text input, for example when you have to display some warnings during form validation. Here's how you can implement a fallback mechanism:

<input type="text" name="email" id="email" />
<noscript>
  <p>The email format must be in the name@domain.extension format.</p>
</noscript>

By doing so, the message will be available even to text browsers that, in addition, don't support CSS neither so that you cannot hide text with CSS properties.

Coming to screen readers, you have to bear in mind that this kind of applications have a very limited support to Ajax and JavaScript in general. Further, since the overwhelming majority of screen reader users generally use keyboard to move through page contents, you have to replace mouse events with keyboard events. But the real problem lies in the content updates performed via Ajax. Screen readers have a feature called virtual memory. By default, this feature is disabled. Without virtual memory turned on, if your content is updated via Ajax, screen readers will restart to read your document from the very beginning. In addition to this, you should always trigger Ajax on elements that can have focus, such as links or form inputs.

In a nutshell, the best thing to do is to implement a solution like the one mentioned above instead of relying on a support that can be very poor or absent.

Performance matters

There are some false myths about performance. One of the most famous is the idea about code optimization. That's wrong. Another myth is the client-side tuning for better results. Wrong too. I've seen many sites with a gnarly and messy code, absolutely lazy in their implementation and non-standard. Result? They weren't slow, even when I used to surf the web with a 800kbs/1Mb connection. What's more, these sites hosted forums, aggregators, and other database-driven applications. And they weren't slow. So what's the point? Bandwidth, server hardware like processor, memory, and other tweaks. In a nutshell: if you want an optimum performance, you should find some good server and a dedicated hosting. Forget all the stuff about shared hosting: that's poor, unsecure and limited. With a little more funds, you'll spare some additional issues.

Semantic CSS breadcrumbs

Generally, breadcrumbs trails are made with the following markup:

<div id="breadcrumbs">
  <a href="#">Home</a> &gt
 <-- Other links -->
 Current section
</div>

Wrong, totally wrong and completely non-semantic, because it doesn't resemble the tree hierarchy of the directories. Here's a better approach:

<ul id="breadcrumbs">
  <li><a href="#">Home</a>

     <ul>
         <li><! -- Another link -->
         
                <ul>
                     
                         <li><strong>Current section</strong></li>         
                     
                </ul>        
         
         </li>
    </ul>

  </li>
</ul>

That's semantic, instead and here's how we can stylize it with CSS:

#breadcrumbs {
  margin: 0;
  padding: 0;
  list-style: none;
}

#breadcrumbs li, #breadcrumbs ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: inline;
}

#breadcrumbs li a {
    padding-right: 0.4em;
    margin-right: 0.3em;
   background: url("img/arrow-right.gif") no-repeat 100% 0;
}

That's it. Hope that helps!

CSS validation is almost useless

Valid CSS! I mean, CSS validation is useful only to detect parsing errors during the development process, but nothing more. To be honest, however, this is something that browsers are able to do by themselves without checking the style sheet with an external resource, because if a CSS file has some syntactic errors, well, it doesn't work as expected. Period. Valid is a different concept. CSS is basically a language with a strong backward compatibility design, so the syntactic differences between versions 2.1 and 3 are only theoretical, because a CSS 2.1 file is also a valid CSS 3 file and vice-versa. So my point is: CSS validation should not be used to show out that your site is cool or standard or just to show this badge that claims "Valid". This is a fad, and it's quickly disappearing. Just perform validation only if you're in doubt about the syntax used. Don't be afraid of using vendor extensions or something like that: they don't hurt! What's more, that can't hurt your visitors.

CSS3 namespace selectors: writing an article

Actually, I can't take a decision: should I write an article in English or in Italian on CSS3 namespace selectors? I made a lot of tests on the subject. Currently, this feature is supported by Firefox, Opera, Safari and Chrome (IE is still hanging on). The fact is that my main web site is a mess: I got both /articles and /articoli directories. What's more, I recently started /appunti... gosh, that's a difficult situation!

So, what one could do with these selectors? Basically, if you have an XML document like this:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.site.com/ns/root" xmlns:test="http://www.site.com/ns/test">
  <element>Foo</element>
  <element:test>Test</element:test>
</root>

you cannot stylize the second child of the root element with a simple type selector, because this element lives inside its own namespace (sure, you could use an adjacent sibling combinator, but what happens if you have more than one element? you'll end up with a neverending chain of plus signs!). So here's why CSS3 namespace selectors are very useful: they allow you to stylize an XML document without having to transform it into HTML by using XSLT. Cool!

Flickr API: getting started

I activated my Flickr API key this very morning and downloaded the documentation. I have to say that this kind of thing is really interesting, because it allows you to create rich mashups with a little effort. I'm not a stickler of the JSON/JavaScript approach, because I think that this kind of format should be handled using a server-side language instead of relying on a client-side support that, as many of you know, is not always available (PHP supports JSON very well, though).

As you can see, this blog integrates Flickr photos, but I don't have access to the full details of the implementation, so the best thing I can do is to write my own code and see it by myself.

JavaScript: Safari vs Firefox

The following video is a little bit obsolete and shows some JavaScript benchmark tests on Safari and Firefox. The guy who made this video doesn't specifiy which version of Safari he is using, but after taking a look at the video date I guess it's still Safari 3 (which doesn't have SFX, by the way). The video description claims: "Guess who wins". Well, I guess it was Firefox at the time but now things are changed. Things change.

Fetching pages with PHP: two different approaches

I played a little bit on my local machine with some content downloaded from Html.it. Basically, I used two different approaches for fetching a page: a stream-based approach and a DOM-driven one. Here's the first:

$edit_posts = file_get_contents('http://blog.html.it/author/gabroman');
$posts = preg_match_all('#<p id="post-\d+"><a\shref="http://blog.html.it/\d+/\d+/\d+/.+">.+</a></p>#', 
$edit_posts, $matches);

foreach($matches[0] as $match) {
$match = preg_replace('#<p id="post-\d+">#', '', $match);
$match = preg_replace('/title=".+"/', '', $match);
$match = preg_replace('#</p>#', '', $match);
echo '<li>' . $match .  '</li>';
}

The DOM approach is quite different:

$html = new DOMDocument();
$html->loadHTMLFile('http://blog.html.it/author/gabroman');

$content = $html->getElementById('content');
$links = $content->getElementsByTagName('a');

foreach($links as $link) {

    $url = $link->getAttribute('href');
    $text = $link->firstChild->nodeValue;
    $posted = $link->parentNode->nextSibling->nextSibling->firstChild->nodeValue;
    
    if(preg_match('#^http://blog.html.it/\d#', $url)) {
    
        echo '  <li><a href="' . $url . '">' . $text . '</a>' . "\n" . '    
 <div>' . $posted . '</div>'. "  </li>\n";
    }
    
    
}

Actually, in order to properly treat special characters, both pages must have the same encoding (the target encoding is UTF-8). However, both approaches rely on the fact that a page structure should remain the same for ever and ever, and obviously this is not the case in a real web!

Why CSS class and ID selectors don't always work in XML

This is a question that sometimes may arise in forums and mailing lists, especially when innocent developers try to stylize their first XML documents. A simple answer to this question is provided by the CSS specification itself, when it states that:

In XML 1.0, the information about which attribute contains an element's IDs is contained in a DTD. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is.

http://www.w3.org/TR/CSS21/selector.html#id-selectors

The same remarks apply to the class attribute as well. Web developers accustomed to XHTML, which has a predefined DTD and stores element attributes in an ATTLIST element, find this difference quite confusing.

They say: "But wait, we can specify a custom DTD for our XML documents, can't we? So if we specify id and class attributes in an ATTLIST, then this problem will be fixed".

Unfortunately, this is far from being the truth. Today's browsers don't use a validating parser, so they don't treat XML attributes as they do with their XHTML counterparts. In other words, even if you specify id and class attributes in your DTD, a browser won't consider them as special attributes (as in XHTML). No "magic" here.

To fix this problem, we should use attribute selectors instead of ID and class selectors: for example, book[id="b1"] instead of #b1, or price[class="special"] instead of .special.

Bear in mind, however, that the specificity of attribute selectors is lower than ID and class selectors, so it may be necessary to add an !important statement to the declarations:

  1. book[id="b1"] {
  2. color: green !important;
  3. }

Opera 10 bug with CSS counters

After installing the latest version of Opera, I pointed that browser to this test page just to see if the bug I've reported a couple of months ago has been fixed or not. Unfortunately, the bug has not been fixed.

This test page has the following markup:

<ol>

<li>Item</li>

<li>Item</li>

<li>Item</li>
</ol>


<div>
<ul>
<li>Filler text</li>
</ul>
</div>

With the following styles:

ol {
 counter-reset: item;
}

ol li {
 display: block;
}

ol li:before {
 counter-increment: item;
 content: counter(item)". ";
}


div ul li {
 display: block;
}

div ul li:first-line {
 color: silver;
}

The bug occurs when you use a :first-line pseudo-element on the same element type that has been used to add counters. As you can see, Opera seems to apply the scope of the ol element to the whole document. Although this kind of behavior is not well defined by the CSS specifications, a bug like this may be really annoying if you stumble on it.

Update

Screenshot in Opera Version 10.50 pre-alpha Build 8174 Platform Mac OS X System 10.4.11:

Thanks to David Laakso!

Notes on CSS and SVG tests

Here are some notes taken from my CSS and SVG tests:

Notes:

  1. Inserting a SVG document in a web page

    Inserting a SVG document through the object element works well in all supporting browsers. Instead, using the img element works only in Safari.

  2. Styling SVG documents

    There's no way to apply CSS 2.1 styles directly to a SVG document (see SVG specifications ). On the contrary, we can work on svg blocks when embed in a (X)HTML or XML document.

  3. Hidden elements

    Certain SVG elements, such as title and desc cannot be rendered on the page. They work in the same way as the elements contained inside the (X)HTML head element.

  4. Using a SVG document as a background image

    Supporting browsers don't allow a SVG document to be used as a background image of an element. So the following code won't work:

    1. element {
    2. background-image: url("file.svg");
    3. }
  5. Positioning

    For positioning, we should always work on the entire svg block. Applying positioning styles on its descendants doesn't work.

  6. The 'text' element

    The text element accepts only font-related properties (font-family, font-weight etc.). Opera needs also 'font-size: 1em'. Otherwise, the text is showed in a smaller font size.

  7. The 'svg' element and the box model

    The svg element accepts borders, background properties and padding. In order to apply also margins, this element must be turned into a block box.

  8. Although Opera and Safari don't support XLink per se, in the case of a SVG document they honor the specified linking (see image-000.xml as testcase).

  9. Internet Explorer's support

    Internet Explorer 7 (and lower) doesn't support SVG. However, when a SVG fragment is embedded in a XML file and there are some CSS styles applied to it, Internet Explorer 7 honors the specified styles, treating the svg element (and its descendants) as normal XML elements, as shown in the following picture ( box-model-fonts-000.xml).

    Internet Explorer 7 and SVG
  10. Not working styles

    Applying the following styles to a polygon element doesn't work. We should use inline styles instead.

    1. polygon {
    2. filter: url(value);
    3. stroke: value;
    4. stroke-width: value;
    5. stroke-opacity: value;
    6. fill: value;
    7. fill-opacity: value;
    8. }

    See complex-000.xml.

Google lesson: less updates, less ranking

I didn't update regularly CSS Zibaldone for several months (from June 2008 to October 2009). Result? My page rank decreased from 6 to 5. Nice lesson. Anyway, I also noticed that the top search queries decreased significantly during this period. Another thing to focus on is the fact that some sections of my site didn't change in content since the beginning. A couple of days ago I started publishing my notes on CSS (in Italian), but Google seems to ignore the newly published content (it has high specificity, though). This section, in fact, is one of those parts that didn't change since now. Lesson learned: update regularly your site, or your page rank will remain low.

jQuery has() selector: a discussion

I had a brief discussion with Boris Zbarsky on www-style about the possibility of implementing the jQuery's E:has(F) selector in the current CSS specification.

Boris correctly pointed out that my proposal would be far from being easy to implement because of the existing differences between JavaScript and other programming languages, such as C++ (the Firefox's source code is actually written in this language, as you can see at http://mxr.mozilla.org).

In a nutshell, JavaScript works with single DOM snapshots, while the CSS parser works with a global token stream (see Firefox's nsCSSScanner.cpp). For example, suppose that we want to stylize an h2 element based on the presence of an a element within it. We could write the following CSS rule:

h2:has(a) {
  color: green;
}

Consider the fact that we're actually working with the following DOM structure:

h2    #element
  a    #element
        #text

To properly select the h2 element, the CSS parser should adopt a DOM approach, that is, it should create a whole object model automatically whenever it parse a style sheet. Naturally, this approach is really expensive because it consumes more memory than a stream-based approach. As in C++, memory consumption in a DOM implementation is dependent on the size of the file, usually O(n).

That's why browsers don't implement the :has selector. Performance is a key aspect when dealing with CSS implementations and browser implementors cannot overlook this issue.

Semantics of XML elements

Although XML is a structured markup language without any predefined DTD, writing semantical XML element names can actually improve the final structure of our document and make our code more readable and easier to maintain. If you're accustomed to the semantics of (X)HTML element names, you've probably noticed that every single element name reflects its own underlying purpose. For example, an em element marks up a normal emphasis, a p element marks up a paragrah and so on.

As said above, in XML we have to write our custom DTD, so the choice of proper element names is crucial. Consider the following example:

<?xml version="1.0" encoding="utf-8"?>
<books>
  <oreilly>
    <book>
      <title>XML. Pocket Reference</title>
      <authors>
        <author>Simon St. Laurent</author>
        <author>Michael Fitzgerald</author>
      </authors>
      <isbn>978-0-596-10050-6</isbn>
      <pages>171</pages>
      <price>9.95</price>
    </book>
<!-- omitted for brevity -->
  </oreilly>
<!-- omitted for brevity -->
</books>

In this example, which resembles the inner structure of database tables, element names are meaningful and descriptive. By doing so, a developer who will probably read your code in the future can easily figure out the structure of your document and grasp the meaning of element names on the fly. However, things start to be more complicated when dealing with mixed content (i.e., elements which contain both text and other elements). In this case, we should avoid the practice of creating a huge amount of elements names, because this practice can create problems with our DTD. Instead, we should rely on custom attributes to add semantics to our elements. For example, if I want to create a level-one heading and a paragraph that contains some text with a normal emphasis, I can write the following:

<?xml version="1.0" encoding="utf-8"?>
<page>
  <heading level="1">Title</heading>
  <para>This is a <emph type="normal">normal</emph> emphasis.</para>
</page>

As you can see, instead of writing heading1, heading2 and so on, we can reduce the amount of code by using custom attributes for our purposes. Notice how the semantics of elements has been preserved.

jQuery and CSS: containing floats

Containing CSS floats can be a really tedious task. Basically, every container with floats should have a rule like the following:

.clearfix {
  overflow: hidden;
  height: 100%; /* IE6 */
}

But with jQuery we can easily avoid to add this class to the markup with a few lines of code:

$(document).ready(function() {
  $('*').each(function() {
    var $element = $(this);
   if($element.css('float') !== 'none') {
      $element.parent().addClass('clearfix');
   }
 });
});

That's all! By doing so, we keep our markup intact and we spare a lot of time! Do more with less: that's jQuery's motto. Isn't it amazing?

CSS comments: how to use them

This post focuses on the use of CSS comments for organizing style sheets. I'll review the most popular practices used so far by web developers, adding some hints based on my personal experience.

Comment syntax

The syntax of CSS comments resembles that used by many high-level programming languages, such as C++, Java or C#. In CSS, comment blocks start with a slash followed by an asterisk and end with an asterisk followed by a slash. This structure is used either in single-line comments or in multiple-lines ones. Here's an example:

/* A single-line comment */

/* Another comment */

/* This comment spans
   multiple
   lines */

CSS comments are ignored by the CSS parser and you can put them everywhere in a style sheet, even inside a rule or declaration. Note that everything appears within a comment is ignored as well, including CSS rules or declarations. We'll see how to take advantage of this aspect in the next section.

Debugging CSS with comments

CSS is not a programming language, so it has no notion of break points (very useful in debugging). However, we can use comments to keep track of our trial-and-error efforts when we have to modify declarations or rules, as shown below:

#articles {
  width: 20%;
  float: right;
}

#articles .latest {
  /* width: 100%; */
  border: 1px solid #ccc;
}

The second rule (line 6) shows a potential rendering problem, because the elements with class .latest have yet a stated dimension that equals the overall width of their container. In this case, the children elements will overflow their parent if they have a larger dimension and this floated box will be pushed down. If we want to keep the one-pixel border, we should remove the declaration at line 6. What if our choice is wrong? We can use comments as a fallback mechanism without deleting and rewriting our code. If our choice is correct, we can remove the comment together with the buggy declaration and move on.

Notes and information

Another use of comments, perhaps obvious, is to write down contextual notes for yourself or your development team. Example:

body {
  font-size: 76%; /* Font-size set to 12px */
}

In that vein, comments can also be used to insert information about a CSS file. Such information are generally put at the very beginning of a style sheet, as the following example shows:

/* File: style.css
   Path: www.css-zibaldone.com/style/style.css
   Author: Gabriele Romanato */

In some of my projects, I've also tried another approach by using JSDoc for commenting CSS. Example:

/* @fileoverview style.css
   @link www.css-zibaldone.com/style/style.css
   @author Gabriele Romanato */

However, not all the features of JSDoc can be applied to CSS, although I think this approach is very interesting.

Grouping rules

Basically, a style sheet is made up by a set of rules. When dealing with big files, it's important to create smaller subsets of rules that share some similarities (e.g., they stylize the same section of a document). Comments can be used in this way to keep our files organized. Example:

/* GENERAL STYLES */
...
/* GLOBAL CONTAINER */
...
/* CONTENT */
...
  /* Main content */
  ...
  /* Secondary content */

As you can see, I follow certain conventions when grouping rules with commments. More specifically, I:

  1. write a supersection in uppercase letters;
  2. write a subsection in lowercase letters and indent it to emphasize the fact that the current section is actually contained withing the preceding supersection.

By doing so, it's easier to grasp the overall structure of the document we're working with.

Comment flags: an improvement

In 2005, Doug Bowman proposed the idea of using a sort of comment flags (i.e., a string of characters) in order to help web developers searching within a style sheet for a specific section or group of rules. His article, that can be found at www.stopdesign.com/log/2005/05/03/css-tip-flags.html, popularized the use of the "=" character as a sort of marker for CSS comments.

Using the search options of your favourite editor, you can easily find all the occurrences of the string "/*=" (or "/*CON") within your CSS file. Simple, smart and amazing, isn't it? The only problem with this solution lies in the fact that it doesn't exist a common nomenclature for the usage of such markers. What if I want to mark up an hack, a bug, a change in the code or a rule used together with some JavaScript library? In that vein, I propose a nomenclature for CSS flags, summarized in the following table.

Table 1. CSS flags nomenclature
Flag Meaning
=B Marks a bug (B) or a problem that needs to be solved.
=C Marks a change (C) or revision in the source.
=F Marks a fix (F) for a bug.
=H Marks a CSS hack (H).
=J Marks a set or rules or declarations that can be used together with JavaScript (J).

Some examples:

#box {
  float: left;
  width: 250px;
  margin-left: 1em;
  display: inline; /*=F Fixes IE's doubled-margin bug */
}

#box h2 {
  font-size: 1.5em; /*=C Changed from 1.4em */
}

#box table tr.even {
  background: #eee; /*=J JavaScript Zebra Tables class */
}

This nomenclature is purely indicative. Feel free to modify it if it doesn't suit your needs.

jQuery CSS Parser: part 1

The final goal of my current project is to write a library that is able to parse a CSS file via Ajax. Wow! Nothing less? Actually, I'm still in beta version. I use a lot of regular expressions to extract comments, properties, values, selectors, etc. When I switch to the final version, I'll get rid of this approach to embrace a more practical, token-based, stream-based way of coding. My inspiration comes from the nsCSSScanner of Firefox (see it here).

jQuery has a lot of helping features. $.grep(), for example, allows you to filter an arrat based on certain criteria. Anyway, I need to use them more. Another source of inspiration is the JSON parser written by Douglas Crockford. That's beatiful. I'm going to publish the beta version soon (probably here). So... stay tuned!

libxml: parsing and writing XML in a snap

I've just finished to download libxml sources and documentation. Here's an excerpt that shows how libxml writes an XML document:

sum = 0;
    count = xmlOutputBufferWriteString(writer->out, "<?xml version=");
    if (count < 0)
        return -1;
    sum += count;
    count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
    if (count < 0)
        return -1;
    sum += count;
    if (version != 0)
        count = xmlOutputBufferWriteString(writer->out, version);
    else
        count = xmlOutputBufferWriteString(writer->out, "1.0");
    if (count < 0)
        return -1;
    sum += count;
    count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
    if (count < 0)
        return -1;
    sum += count;
    if (writer->out->encoder != 0) {
        count = xmlOutputBufferWriteString(writer->out, " encoding=");
        if (count < 0)
            return -1;
        sum += count;
        count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
        if (count < 0)
            return -1;
        sum += count;
        count =
            xmlOutputBufferWriteString(writer->out,
                                       writer->out->encoder->name);
        if (count < 0)
            return -1;
        sum += count;
        count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
        if (count < 0)
            return -1;
        sum += count;
    }

    if (standalone != 0) {
        count = xmlOutputBufferWriteString(writer->out, " standalone=");
        if (count < 0)
            return -1;
        sum += count;
        count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
        if (count < 0)
            return -1;
        sum += count;
        count = xmlOutputBufferWriteString(writer->out, standalone);
        if (count < 0)
            return -1;
        sum += count;
        count = xmlOutputBufferWrite(writer->out, 1, &writer->qchar);
        if (count < 0)
            return -1;
        sum += count;
    }

    count = xmlOutputBufferWriteString(writer->out, "?>\n");
    if (count < 0)
        return -1;
    sum += count;

    return sum;

This is a buffered stream-based approach with strings. How fast is it? Believe me, it's faster than light!

CSS is too loose

I've been testing CSS for quite a lot during these years, giving significant tests to the W3C test suite. My conclusions are summarized in this sentence: nowadays CSS is too loose. Here are some critical issues that need to be solved:

  1. there are no rules to detect the CSS version you're using. CSS3 introduced the '::' syntax to tokenize a pseudo-element. Browsers that support the CSS3 syntax follow both grammars (CSS 2.1 and 3), even if a stylesheet contains mixed rules. I proposed the @profile media rule to help browsers with choosing a grammar to follow, but my proposal was rejected.
  2. CSS quotes are still a mistery. Some browsers apply a rule even when there's an occurrence of multiple nested quotes, such as in url("'foo.gif'") and in other CSS functions.
  3. CSS generated counters are still buggy in some particular cases of nested scopes and conflict between pseudo-elements in a given scope (see this test in Opera for example).
  4. cascading, specificity and DOM scripting: this is another area for testing, but the current view of many implementors is that this kind of tests should be avoided.
  5. the ';' is optional when a rule contains only a declaration. Better if it was always mandatory, just like some programming languages.

In my opinion, CSS should be more restrictive in their form. By doing so, we actually reduce the likelihood of inconsistencies.

How to purchase Adobe Dreamweaver CS4: an odissey

That's frustrating, but in order to purchase Adobe Dreamweaver CS4 and download it, you have to come from USA, Mexico or Canada! These are the available options. By the way, you have also to specify the correct ZIP and Area code, because this kind of data will be checked before the transaction! Gee, I'm from Italy! Why my country is not included? Sure, I went to the Italian web site of Adobe but they redirect me to the US counterpart. So my order could not be processed and I still wonder why the concept of internationalization is so hard to be accomplished in the real web. Ok, this is not the end of the world but I think that a big and reliable company such as Adobe should take this issue into account.

Google and the white-space between keywords

A thing that recently strucked me about Google is the relevance of white-space between keywords. This is really relevant in queries. Although many people think that if you choose a name such as "foobar" Google will be able to make a distinction between the two, this is not the case when you enter "foo bar" in a search query. I've experienced this behavior myself by naming a directory "ie6fix". I expected to see a query like "ie6 fix" working well, but unfortunately it didn't work: Google indexed my document as "ie6fix", not as "ie6 fix".Try to run queries like "jquery ie6 fix" and "jquery ie6fix" and you will see it by yourself. Moral: white-space is relevant even when we choose a name to give to our documents.

Email validation in PHP: well-formedness vs existence

As this post correctly points out, only checking if an email address is well-formed is not sufficient (especially if you check it against the RFC specification.. the PCRE regular expression for accomplish this task may be a real nightmare - see PHP Cookbook for instance). We should also check if the email address is active by querying its DNS server.

Although this approach could seem feasible and correct, I think that we should always ask if it's necessary first. For example, if a customer wants to download a document and the link for downloading that file will be provided via email, why in the world should he/she provide a false/incorrect email address? Again: if someone signs up to a social network and the platform send him/her a link to activate his/her account, why should he/she try to fake it? Simply put, sometimes there are situations in which we should trust user input (though we must always filter it, of course). Moreover, querying a DNS server on a busy production server may be even expensive than a simple regular expression.

Extending XHTML

According to the meaning of the acronym, XHTML should be an extensible markup language. The sad truth is that XHTML is by far a language that is not so easy to extend. Basically, XHTML is built on 4 DTDs (3 for XHTML 1.0 and 1 for XHTML 1.1) that allow only a restricted set of elements to be used. Take for example the Blogger declaration of a DTD:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' 
xmlns:data='http://www.google.com/2005/gml/data' 
xmlns:expr='http://www.google.com/2005/gml/expr'>

Despite of the fact that some additional namespaces have been declared, the above DTD declaration doesn't allow additional elements on the page. . Even more oddly, browsers use a non-validating parser. so using the above declaration doesn't make any difference to them. If XHTML was truly extensible, one could write something like this:

<!DOCTYPE html PUBLIC extended "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-extended.dtd">

By doing so, we can use new elements on the page, for example those that belong to the Blogger namespace. Instead, we still have to use a common set of elements that certainly doesn't lead XHTML to its full potential.

The image element in RSS

Speaking theoretically, the image element in RSS should be used to insert graphics into an RSS feed. Just theoretically! In fact, according to some tests made during the writing of an RSS guide for Html.it, this element works only in Firefox. What's more, Firefox accepts it only when it's put in a a direct descendant of the channel element. That is, it doesn't work in an item element. Developers are then forced to use the string &lt;img /&gt; to insert an image into their RSS feed. Oh well...

My lazy style in programming

Here are my usual mystakes during programming:

  1. mismatching syntax (parentheses, braces, etc.)
  2. I often forget variable names and built-in functions
  3. I often use methods and functions with wrong parameters
  4. I often crash browsers with endless loops
  5. I usually forget to use proper indentation (although I comment my code very well and appropriately.. oh, I think it's Scite's fault.. that's an excuse)
  6. I'm still looking for the perfect programming editor (if it does exist).

And yours?

Facebook is almost inaccessible

I've been involved in accessibility studies for almost three years and I have to say that Facebook is not exactly the perfect prototype of an accessible web platform. This is due to the following reasons:

  1. Proprietary markup used in APIs

    Instead of using Microformats, Facebook's APIs rely on proprietary markup to make the application work. This leads to poor interoperability betwenn different user-agents.

  2. Massive use of JavaScript and Ajax

    Without a proper fallback mechanism, these two technologies can actually make life very hard for people with disabilities or people who use assistive technologies.

I hope that in a near future Facebook will take into account these issues more seriously. Meanwhile, people with disabilities may experience a genuine frustration in trying to use this platform.

Automation server can't create object in Internet Explorer 8

Bad news are always bad news. I've tested the get and ajax features of jQuery in Internet Explorer 8 with XML files and I've found out that IE8 sometimes returns the infamous "Automation server can't create object" error. This error is related with the internal linking of IE8 to some libraries of the .NET Framework installed on the client machine. So if these libraries are not updated or the linking is somewhat corrupted or broken, IE8 will return the aforementioned error. Oh, but there are also good news: traditional parsing of an XMLDocument object with the usual Ajax routines coded by hand works well and also the Ajax features of Prototype (e.g. Ajax.Request). I'm sorry. Anyway, that's not jQuery's fault.

CSS box model: rethinking the specifications

The CSS box model has been misunderstood for years. I think that the main problem with the CSS specification lies in the fact that borders, margins and padding are treated as separate arguments from width and height properties. Take a look at this picture for example:

CSS box model

It's still hard for web developers to figure out what happens when height and width measures are added to this model. Basically, you have to think it along two axes, horizontal (width) and vertical(height). For the first you have to sum up left and right margins, borders and padding plus width; for the latter, instead, the overall measure is given by the sum of top and bottom margins, borders and padding plus height. These are the measures of the whole containing block.

Remember that also when you use the top, right, bottom and left properties of positioning you add other measures to the mix. Be careful then!

iTunes and the infinite development

I really appreciate the fact that a web service and application such as iTunes has so many features to share with web developers. The development behind iTunes is infinite, in the sense that is a work in progress with a real purpose: to make users happier and happier. A couple of months ago I downloaded some guides and tutorials about iTunes APIs, but I never really tested anything. The sad thruth is that I was forced to deal with Windows/IE oddities in order to make my code work with these platforms and devices. Oh, by the way, I think that Cocoa is great! I only need more spare time to study it. Ettore that it's simply powerful and brilliant. Ok, so...

CSS3: multiple background images bug?

I was testing the following markup:

<div>
  <h3>Title</h3>
  <p>...</p>
</div>

with the following styles:

div {
  background: #ccc url(topleft.gif) 0 0, url(topright.gif) 100% 0, url(bottomleft.gif) 0 100%, url(bottomright.gif) 100% 100%;
  background-repeat: no-repeat;
  width: 240px;
  padding: 10px;
}

This way, the entire box with all its content disappears in all browsers, even in those that don't support multiple background images. Am I missing something?

Update

http://lists.w3.org/Archives/Public/public-css-testsuite/2010Feb/0017.html. Yes, I was missing something!

Jquery's font sizer and Internet Explorer

I found out that the following code doesn't work in Internet Explorer:

function setFontSize() {

   // it doesn't work in IE
  
   $('<div id="font-sizer"><<div>').
   html('<strong>Adjust font size:</strong> 
<a href="#" class="increaseFont">Increase</a> 
<span>|</span> <a href="#" class="decreaseFont">Decrease</a> 
<span>|</span> <a href="#" class="resetFont">Reset</a>').
   appendTo('body');
   
   
  var originalFontSize = $('body').css('font-size');
  $(".resetFont").click(function(){
  $('body').animate({fontSize: originalFontSize},600);
  return false;
  });
  $(".increaseFont").click(function(){
   var currentFontSize = $('body').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 1.2;
 $('body').animate({fontSize: newFontSize},600);
 return false;
  });
  $(".decreaseFont").click(function(){
   var currentFontSize = $('body').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 0.8;
 $('body').animate({fontSize: newFontSize},600);
 return false;
  });
  
 }

Internet Explorer shows enormous variations during the resizing. Any ideas?

Firefox 3.6 source code: part 2

Some major changes at first glance:

  1. nsSpaceManager's gone. The SpaceManager handled CSS floats
  2. html.css now includes also style rules for the HTML 5 video element
  3. new headers and classes for handling the newly supported CSS features (such as media queries; see /layout/style)

Documentation is still obsolete, but new test cases have been added (all taken from Bugzilla reports.

Private properties in JavaScript

JavaScript lacks of the classical OO keywords like public, protected and private, so a developer is forced to use scope in order to implement something that mimics the basic behavior of such keywords. For example, a good way to implement private members in a JavaScript class (although in JavaScript there are only functions, not classes in the strict sense of the term) is the following:

function MyClass {
  var url = location.href;
  var title = document.title;
  var ua = navigator.userAgent;

  this.setPermanentLink = function() {
    $('<p class="permalink"></p>').html(' <a href="' + url + '">Permanent link</a>').
    appendTo('#site-info');
  };
  
  //...
}

Since the first three variables lie in the function scope, they're not accessible from outside the function/class. Perhaps I'm reinventing the wheel, but this is one of the most frequently asked questions of ever (especially among traditional OO programmers).