boogdesign posts

Longer posts on standards based web design, portable web development and Linux, intermingled with some stuff on my other nerd interests.

Rob Crowther, London, UK based Blogger, Web Developer, Web Designer and System Administrator - read my Curriculum Vitae

Buy my book!

Book CoverHello! HTML5 and CSS3 available now

Buy my other book!

Book CoverEarly access to HTML5 in Action available now

Category: Front End Web Development

03/06/11

02:51:00 pm Permalink Drag and Drop and Delegate

Categories: Front End Web Development, Blogging and Internet Culture

HTML5 Drag and Drop has been popular topic recently on web tech blogs, a good example is Alexis Goldstein's post on Sitepoint which I converted to work in IE. Fortunately for me this all coincided with spending a lot of time working on Drag and Drop for chapter 6 of my book and a project coming up at work where it was a natural fit. So I've been doing a lot of dragging and dropping in recent weeks, to the point where I started to feel like I knew as much about the practical implementation of the Drag and Drop API as any person living.

Of course, whenever I start getting a bit full of myself something soon happens to make me feel like an idiot again. In this case it's my continuing blind spot when it comes to DOM Event Delegation. If you look again at Alexis' example you'll note that all the event handlers are bound directly to the elements where the events are expected to happen. This is a common pattern in example code - it's a straightforward relationship for beginners to understand - but it's not really the best way to do it, and this post is going to explain why. Let's review the code for the drop event:

$('#todo, #inprogress, #done').bind('drop', function(event) {
    var notecard = event.originalEvent.dataTransfer.getData("text/plain");
    event.target.appendChild(document.getElementById(notecard));
    event.preventDefault();
});

What this code does is bind a drop handler to three separate elements specified by the IDs in the selector - #todo, #inprogress, #done. Now have a look at this screenshot of the original planning board in action:

A task embedded within another task

The task 'Learn HTML5' as been dropped directly inside the task 'Learn CSS3' and the 'Learn CSS3' task accepted the drop and ran the drop handler code despite not being mentioned above - why? The answer is because of event delegation. While in this particular case it may look like a bug, this is actually a very powerful and useful process. Here's what's happening when the 'Learn HTML5' task is dropped:

  1. The drop event is fired on the 'Learn CSS3' element
  2. Because there is no drop handler, the event is passed up the document tree< to the parent element - in this case #inprogress
  3. There is a drop handler on the #inprogress, so that handler is run

This process is called event bubbling - the events rise up through the DOM tree like bubbles through water, and the consequence of the bubbling here is that the event is fired on the 'Learn CSS3' element, which remains the target of the event, but it's processed by the event handler on the #inprogress element. Because the handler just says 'append the dragged element as a child of the event target' the 'Learn HTML5' element is added as the last child of 'Learn CSS3'.

Initially you might see this as a bug, but really it's an opportunity. As long as we deal with this unwanted side effect we're freed from having to attach event handlers to every single element. If this doesn't seem like a huge gain, consider these two scenarios:

  1. You want to scale up to handle have a large number of draggable items and drop targets, into the thousands
  2. You want to add and remove draggable items and drop targets dynamically

The first scenario was the one I found myself in with my work project - the drop targets were cells in a table, with over fifty columns and possibly hundreds of rows, and 30-50% of those cells had draggable items in. When I started with the naive approach of binding a handler to each item it took a second or two to run the initialisation code in the good browsers (in IE8 it took nearly 30 seconds...). Event delegation helps in this scenario because the number of events you have to bind is equal to the number of events you want to capture, not the number of elements you want to capture them on.

It's unlikely an agile planning board is going to end up with that many elements though - if it does I suspect there's a good chance you're not really being agile, but the second scenario is more likely to come up. The tasks and the available resources will likely change from sprint to sprint, you may also want to add in some extra statuses. With the current code, every time you want to add an element you will have to attach all the relevant event handlers to it (even if jQuery makes that easy for you, that could still be a lot of overhead). If you forget to do that in a particular code path then strange bugs will likely ensue, which is a shame when all you really want is for the new elements to execute the exact same handlers as all the existing ones. Let's look at how easy this all becomes if you don't try to bind event handlers to every single element.

First, some adjustments to the markup. Because there'll now (potentially) be multiple rows on the board we can't use id attributes to distinguish them so they'll have to be a class. We'll also add a 'row title' for the developer name, and

<div id="board">
    <div id="rob">
        <h1 class="title">Rob</h1>
        <div class="todo droptarget">
            <h2 class="title">To Do</h1>
            <a id="item1" draggable="true" href="#">
                <div class="cardTitle">
                    Learn HTML5
                </div>
            </a>
            <a id="item2" draggable="true" href="#">
                <div class="cardTitle">
                    Learn CSS3
                </div>
            </a>
        </div>
        <div class="inprogress droptarget">
            <h2 class="title">In Progress</h1>
        </div>
        <div class="done droptarget">
            <h2 class="title">Done</h1>
        </div>
    </div>
</div>

I've also added a class droptarget to make life easier in the event handlers. Those event handlers will, of course, have to change. Here's a before and after of the dragstart handler:

Before

$('#item1, #item2').bind('dragstart',
  function(event) {
    event.originalEvent.dataTransfer.setData(
        "Text", 
        event.target.getAttribute('id')
    );
});

After

$('#board').bind('dragstart',
  function(event) {
    event.originalEvent.dataTransfer.setData(
        "Text", 
        $(event.target).closest('a[id]').attr('id')
    );
});

The first, and most important, change is that the event is now attached to the #board element instead of to each individual draggable item. The second change is instead of assuming the event target is the planning item the code now looks for the closest parent element which matches what the draggable element is expected to look like. The next event to consider is dragover, here things are slightly more complicated:

Before

$('#todo, #inprogress, #done').bind('dragover', 
    function(event) {
        event.preventDefault();
});

After

$('#board').bind('dragover', function(event) {
    if ($(event.target)
          .closest('.droptarget')
          .hasClass('droptarget')) {
	      event.preventDefault();
    }
});

Now that the handler is being attached to #board every element will trigger the dragoverdroptarget class added earlier. Finally let's consider the drop event:

Before

$('#todo, #inprogress, #done')
  .bind('drop', 
    function(event) {
        var notecard = event
                .originalEvent
                .dataTransfer.getData("Text");
        event.target.appendChild(
            document.getElementById(notecard)
        );
        event.preventDefault();
  });

After

$('#board').bind('drop', function(event) {
    var notecard = event
            .originalEvent
            .dataTransfer.getData("Text");
    var drop = $(event.target).closest('.droptarget');
    drop.append($('#' + notecard));
    event.preventDefault();
});

Although every element which is a descendant of #board could potentially trigger this event, in practice it's only ever going to be the ones that triggered the event.preventDefault() on the dragover event - anything with class .droptarget or it's descendants. Instead of just assuming the target is where the dropped element has to be attached the closest ancestor with the right class is used, so we never end up with dropped tasks getting appended inside other tasks.

I think you'll agree it isn't really much more difficult to write the event handlers in such a way that they take advantage of event bubbling and so only need to be attached to a single element. Now that these changes have been made it's possible to add further developers, statuses or tasks just by generating and appending the appropriate HTML - no need to loop through the new elements and attach all the correct event handlers.

This example page adds several buttons for dynamically updating the planning board, just to show how easy it is. The code is also available on github.


Tweet this!
Send feedback »PermalinkPermalink

20/04/11

01:16:00 am Permalink IE10 and the Future of CSS Layout

Categories: Front End Web Development, Standards, HTML and CSS, Blogging and Internet Culture

Last week the first developer preview of IE10 was released. Among several experimental features included were the first Microsoft implementations of CSS3 Flexible Box Layout Module and CSS3 Grid Alignment. These are possibly the most exciting things to be added to CSS since drop shadows...

First up the flexible box layout module, or flexboxes. This has already been implemented in Firefox and WebKit, but that version of flexboxes isn't very intuitive, and the draft has since seen a lot of updates. Interestingly, IE10PR1 implements the same version of the spec as Firefox and WebKit but with one important addition: multi-line flexboxes. For me the multi-line properties are what make flexboxes worthwhile for layout, otherwise nearly everything you might currently want to achieve can be done just as easily (and with better backwards compatibility) with display: table-cell.

This is the sort of thing that multi-line flexboxes are useful for, it's a layout typical of shopping and photo gallery sites:

A multiline flexbox layout at 800 pixels width

Here's what my markup looks like, nothing more complex than a list with sixty items in it:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    ...
    <li>59</li>
    <li>60</li>
</ul>

And here's the CSS, the key things to look out for are the display: -ms-box and the -ms-box-lines:

body {
    width: 90%;
    margin: 0 5%;
}
ul {
    display: -ms-box;
    -ms-box-lines: multiple;
    list-style: none;
    width: auto;
    padding: 10px;
    border: 4px dashed #000;
}
li {
    display: block;
    -ms-box-flex: 1;
    padding: 1em;
    margin: 0.5em;
    min-width: 3em;
    border: 4px dashed #000;
}

You may be thinking that's not a hard thing to pull off, so let me show you the same page, in an 800 pixel wide browser above, at 640 and 480 pixels:

A multiline flexbox layout at 640 pixels width

A multiline flexbox layout at 480 pixels width

The number of cells across adjusts to match the width available, but, because these are flexboxes, the width of the elements themselves also adjust so that they always exactly fit the available width. This is unique among our current alternatives:

  • If you were using floats or inline blocks then you'd have to set each element to a fixed width, meaning the container would have to be a fixed width so that the elements could fill it exactly. You'd have to use media queries to assign different fixed widths to the container to change the items per row according to screen resolution.
  • If you were using a layout table or display: table-cell then, although the elements would expand to fit exactly, the number of items per row would be fixed by the markup.

However, nothing is perfect. My multi-line flexbox example has a total of 60 elements, and I picked this number because it is an exact multiple of 2, 3, 4, 5 and 6 (it's the expansion of them if I've got my maths terms right&amp;#58;&amp;#63;&amp;#58;) - meaning that the number of elements will fill the grid whether there's 2, 3, 4, 5 or 6 elements per row. If there's a less perfect number, say 24, then the grid will look a little strange on the last row:

A multiline flexbox layout at 640 pixels width with only 24 elements

I think the box-align property should help with this, but I couldn't make it work in IE10PR1.

So, multi-line flexboxes could be a useful addition to the CSS toolbox when everyone gets round to upgrading to IE10, but, cool as they are, that's not the coolest experimental CSS layout implementation in IE10PR1. There have been a few grid and template based CSS proposals over the years but, apart from an incomplete JavaScript library for CSS Template Layout, none of them have ever been implemented in a major desktop browser. That is until last week, when IE10PR1 implemented Microsoft's own CSS Grid Align proposal from October 2010.

I want you to reflect, now, on all the fun you've had over the last ten years constructing CSS layouts of three equal height columns, with a header and footer, and making them work in IE6. Layouts something like this:

A three column layout with header and footer

Are you remembering all the fun you had? Good, now look at this markup and contemplate how you'd turn it into a three column layout:

<header>Header</header>
<aside class="b">Side bar</aside>
<article>I never am really satisfied...</article>
<aside class="d">Side bar</aside>
<footer>Footer</footer>

Now look at this CSS and start wishing the future would arrive soon:

body {
    width: 90%;
    margin: 0 5%;
    display: -ms-grid;
    -ms-grid-columns: auto minmax(min-content, 1fr) auto;
    -ms-grid-rows: auto minmax(min-content, 1fr) auto;
}
article, aside, header, footer {
    margin: 1em;
    padding: 1em;
    outline: 4px dashed black;
}
header { -ms-grid-column: 1; -ms-grid-row: 1; -ms-grid-column-span: 3; }
aside.b { -ms-grid-column: 1; -ms-grid-row: 2; }
article { -ms-grid-column: 2; -ms-grid-row: 2; }
aside.d { -ms-grid-column: 3; -ms-grid-row: 2; }
footer { -ms-grid-column: 1; -ms-grid-row: 3; -ms-grid-column-span: 3; }

That's it, seven declarations is all you need for that three column layout with CSS Grid Align. For this first example I'm going to step through the key points line by line:

display: -ms-grid;

This is the bit which declares we will use the grid layout manager on the children of this element, in the same way that the flexbox layout manager was declared above with display: -ms-box.

-ms-grid-columns: auto minmax(min-content, 1fr) auto;

This line defines three columns, the first and last will shrink to fit the content - that's the default behaviour, similar to a table. The middle column will be a minimum of min-content, which is basically the same as auto, and a maximum of 1fr which is a 'fraction of available space' - quite similar to a flex unit and, since there's only one fractional column, basically equivalent to all the available space.

-ms-grid-rows: auto minmax(min-content, 1fr) auto;

We'll have three rows to go along with our three columns, I won't go over the individual values again. Now the fun stuff:

header { -ms-grid-column: 1; -ms-grid-row: 1; -ms-grid-column-span: 3; }

Put the header in the first column of the first row, and make it span three columns. That's it. Really, it's that simple. Let's just do one more:

article { -ms-grid-column: 2; -ms-grid-row: 2; }

Put the article in the second column and the second row. And make me some coffee, white, no sugar. Actually there isn't a CSS property for that yet, maybe CSS4...

But it gets more cool than that. In the example above the order of the elements in the markup matched up with the order they were placed into the grid, but it doesn't have to be that way:

A three column layout with header and footer, with elements placed in a different order

This amazing transformation was achieved without any changes in markup, just messing around with CSS:

header { -ms-grid-column: 1; -ms-grid-row: 2; }
aside.b { -ms-grid-column: 2; -ms-grid-row: 2; }
article { -ms-grid-column: 1; -ms-grid-row: 1; -ms-grid-column-span: 3; }
aside.d { -ms-grid-column: 1; -ms-grid-row: 3; -ms-grid-column-span: 3; }
footer { -ms-grid-column: 3; -ms-grid-row: 2; }

In the current draft there's a grid-cell-stacking property which will let you flow multiple elements into a single cell, but in the IE10PR1 implementation things just stack on top of each other:

Multiple elements in cells not working

This is a shame, because the markup is quite straightforward, I won't post all of it because this is already getting quite long (have a look), but here's the nice bit:

article:nth-child(2n+1) { -ms-grid-column: 1; }
article:nth-child(2n) { -ms-grid-column: 2; }

The article elements are assigned to grid cells alternately, unfortunately it doesn't work yet. However you can nest elements set to display: -ms-grid inside each other:

A three column layout with header and footer

Have a look at the source code for that one, it gets pretty hairy, so rather than try and do that sort of thing it's probably best to use some wrapper elements like this:

Grid Align with wrapper elements for cells

Again, view the source code yourself to see how it's put together, but I think these things will be worth re-visiting in a later preview release.

I'm going to finish off with some adaptive layout. Grid Align is a great fit for this because of the complete independence of layout from source order. Here's what I put together based off the previous example at 800 pixel width:

An adaptive Grid Align at 800px width

Now here's the same page at 640 and 480 pixel widths:

An adaptive Grid Align at 640px width

An adaptive Grid Align at 480px width

The markup is, of course, the same in each case:

<header>Header</header>
<div id="sidebar">
    <aside>Side bar 1</aside>
    <aside>Side bar 2</aside>
</div>
<div id="content1">
    <article>Content 1</article>
    <article>Content 3</article>
    <article>Content 5</article>
</div>
<div id="content2">
    <article>Content 2</article>
    <article>Content 4</article>
    <article>Content 6</article>
</div>
<footer>Footer</footer>

By default I've assumed a single column layout:

body {
    width: 90%;
    height: 90%;
    margin: 0 5%;
    display: -ms-grid;
    -ms-grid-rows: auto;
    -ms-grid-columns: 1fr;
}
article, aside, header, footer {
     margin: 1em;
     padding: 1em;
     outline: 4px dashed black;
}
header { -ms-grid-row: 1; }
#sidebar { -ms-grid-row: 3; }
#content1 { -ms-grid-row: 2; }
#content2 { -ms-grid-row: 4; }
footer {  -ms-grid-row: 5; }

Moving on to windows of a minimum width of 600 pixels, move up to two columns:

@media screen and (min-width: 600px) {
    body {
        -ms-grid-columns: auto 1fr;
        -ms-grid-rows: auto 1fr 1fr auto;
    }
    header { -ms-grid-column: 1; -ms-grid-row: 1; -ms-grid-column-span: 2; }
    #sidebar { -ms-grid-column: 1; -ms-grid-row: 2; -ms-grid-rowspan: 2; }
    #content1 { -ms-grid-column: 2; -ms-grid-row: 2; }
    #content2 { -ms-grid-column: 2; -ms-grid-row: 3; }
    footer { -ms-grid-column: 1; -ms-grid-row: 4; -ms-grid-column-span: 2; }
}

This is nothing you haven't seen already, but I'll just point out again how cool it is that you can place the elements wherever you want them. Finally, for windows of greater than 760 pixels width, switch back to the three column layout:

@media screen and (min-width: 760px) {
    body {
        -ms-grid-columns: auto 1fr 1fr;
        -ms-grid-rows: auto 1fr auto;
    }
    header { -ms-grid-column: 1; -ms-grid-row: 1; -ms-grid-column-span: 3; }
    #sidebar { -ms-grid-column: 1; -ms-grid-row: 2; }
    #content1 { -ms-grid-column: 2; -ms-grid-row: 2; }
    #content2 { -ms-grid-column: 3; -ms-grid-row: 2; }
    footer { -ms-grid-column: 1; -ms-grid-row: 3; -ms-grid-column-span: 3; }
}

If you've downloaded the IE10 developer preview have a play round with it yourself, and try not to think about how long you'll have to wait until all this stuff is available in production browsers &amp;#58;&amp;#112;


Tweet this!
Send feedback »PermalinkPermalink

31/01/11

01:32:00 am Permalink Client Side Server Side Includes

Categories: Front End Web Development, Blogging and Internet Culture

I spent some time over Xmas reflecting on my past web adventures. My first ever website, a guide to local drinking establishments, was hosted on a cast-off server at Edinburgh University in late 1993, and the particular server and site are now long gone (although the server has been replaced). Similarly, my original mid-nineties home page, replete with animated GIFs and ripped off Homer Simpson images has also be consigned to the recycle bin of web history (thankfully). However, the first website I worked on 'professionally' is still online: iwant2bhealthy.com is a thousand page static HTML monolith which we maintained with Dreamweaver 3.

The site did take advantage of some server processing, it used Server Side Includes (SSI) to embed particular common items such as the main navigation and footer. SSI isn't so common these days when nearly every cheap host offers some sort of server side scripting language, so often it isn't turned on my default. The result is that the iwant2bhealthy.com website is missing its main navigation and footer on most pages, all that's left is some markup like this:

<!--#include virtual="/Library/mainmenu.shtml" -->

Or this:

<!--#include virtual="/Library/footer.shtml" -->

I had a hankering to experience the website in all its turn of the century glory and it seemed to me that I ought to be able write a bookmarklet to grab jQuery, grab the comments, fetch the includes with AJAX and insert them in place of the comments.

It turns out that the first tricky thing is grabbing the comment elements. The jQuery selection engine purposely ignores comments so none of those handy little methods are much use. There's not much option but to loop through the document and select based on nodeType (8 for a comment element), fortunately someone on the web had already done most of the hard work so I was able to adapt his code:

parseSSI : function(el) {
    var nodes = el.childNodes;
    var l = nodes.length;
    while (l--) {
        current = nodes[l];
        if (current.nodeType == 8) {
            //do stuff here
        } else if (current.nodeType != 3 && current.childElementCount > 0) {
            this.parseSSI(current);
        }
    }
}

The function loops through all the child nodes of a supplied element and, if they're a comment, does some processing. If the node isn't a comment we check that it's also not a text node and then call the function recursively if there are any child nodes.

Of course it's entirely possible that there are comments in the web page that have nothing to do with server side includes, so some sort of check is probably in order. Following James' example I used a regular expression:

re : /#include virtual=\"(.*)\"/i

My next step was to convert those comment elements into something that could be more easily manipulated by jQuery, so I decided to convert them to links:

var match = this.re.exec(current.data);
if (match != null) {
    var a = document.createElement('a');
    a.href = match[1];
    current.parentNode.replaceChild(a, current);

Now we're back in the nice, succinct land of jQuery - fetch the URL with Ajax and replace the relevant link element in the callback:

$.ajax({ url: match[1],
         success: function(data, textStatus, XMLHttpRequest){
            $('[href=' + this.url + ']').replaceWith(data);
        }});

Try out the final code here.


Tweet this!
Send feedback »PermalinkPermalink

16/12/10

01:58:42 am Permalink Fun with HTML5 Forms

Categories: Front End Web Development, Standards, HTML and CSS

There have been many blog posts describing all the new elements and input types HTML5 provides, check out this 24ways post for a good summary, or you could even read chapter 3 of my book. In this post I'm going to focus instead on the validation API and some related HTML5 features by building a simple game based on entering an email address. The goal is to explore some HTML5 features rather than do everything in the most straightforward way, but there should be some practically useful code snippets.

The form itself is going to be very straightforward:

<form id="game">
    <fieldset>
        <legend>Enter a valid email address before the timer runs down</legend>
        <label for="email">Email</label>
        <input id="email" type="email" autofocus required>
    </fieldset>
    <label for="countdown">You have
        <output id="countdown">10</output>
        seconds.
    </label>
    <label for="score">You have
        <output id="score">0</output>
        points.
    </label>
</form>

In the initial version we will take advantage of three HTML5 features:

  • The output element
  • The email input type
  • The checkValidity method from the the HTML5 Form Validation API

In the countdown function we use the value property of the the output element The output element is something like a span, it's a start and end tag with arbitrary content, but you can access the contents using the value attribute like a form field :

var counter = function (cd, sc, em) {
    cd.value -= 1;
    sc.value = calcScore(em.value);
}

This may not look particularly helpful, but consider what the code would look like without the output element (or in a browser which doesn't support output):

var counter = function (cd, sc, em) {
    var count = cd.innerHTML;
	count -= 1;
    cd.innerHTML = count;
	sc.innerHTML = calcScore(em.innerHTML);
}

The function is now mostly about the details of manipulating the DOM, rather than the more straightforward algebraic style of the original. Granted, libraries like jQuery have for a long time provided abstractions which allow you to write this code more cleanly but, like design patterns, these are as much an indication of the lack of expressiveness in the underlying platform as they are examples of best practice.

The game needs a function to calculate a 'score' from the email address. This is, of course, completely arbitrary:


function calcScore(email) {
    var s = 0;
    s += email.length;
    s += email.indexOf('@')>-1?email.indexOf('@'):0;
    s += email.lastIndexOf('.')>-1?email.lastIndexOf('.'):0;
    return s;
}

Now we need to wire up the functions to appropriate events when the game starts. To keep things simple I'm going to store a reference to the interval in a global variable:

var cdInterval;
var gameStart = function () {
    window.clearInterval(cdInterval);
    var em = document.getElementById('email');
    var cd = document.getElementById('countdown');
    var sc = document.getElementById('score');
    cd.value = 10;
    sc.value = 0;
    em.value = '';
    em.readOnly = false;
    cdInterval = window.setInterval(counter,1000, cd, sc, em);
    window.setTimeout(gameOver,10000, cd, sc, em);
}

Again, this function takes advantage of the value attribute on the output elements. The last line calls a gameOver function after ten seconds, we'll use that to clear the interval and calculate the score. The checkValidity method of the email field will be used to determine if the email address is currently valid:

var gameOver = function (cd, sc, em) {
    window.clearInterval(cdInterval);
    var score = calcScore(em.value);
    if (!em.checkValidity()) {
        score = 0;
        window.alert("You lose!");
    }
    cd.value = 0;
    sc.value = score;
    em.readOnly = true;
}

The checkValidity() method is part of the HTML5 validation API, it returns true if the browser understands the contents of the field as a valid email. Note that we are able to call this method without submitting the form, so it is easy to hook form submission into a custom validation function if we want. At no point do we have to implement any code to determine what a valid email address would be. This is a second major saving, have a look at this regular expression example if you thought that code was straightforward:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Finally, start the game when the page loads:

window.addEventListener('load', gameStart, false);

The first version of the game will work in Opera, and the development versions of Firefox (4 - relevant bugs are 345624 and 346485 ) and Chrome (9 - relevant bugs are 27452 and 29363). If you want it to work on older versions of Chrome and Safari then you'll need to replace the output based syntax with the innerHTML approach as per the alternate version of counter above.

For the second iteration we're going to look at these two features:

  • Using the pageshow event from the History API
  • How to reset output elements

If the user visits another page after completing the game and then goes back then the game will sit there inert until you reload the page. This is because the game logic hangs off the onload event, and navigating forward and backwards in the browser history doesn't fire onload. The HTML5 History API gives us another option: the onpageshow event. This fires whenever a page is displayed rather than when it is loaded. There is currently support for onpageshow in Firefox and Chrome, but not in Opera, so we'll use the iseventsupported script to detect support and fall back to onload if it's not available:

if (isEventSupported('pageshow')) {
    window.addEventListener('pageshow', gameStart, false);
} else {
    window.addEventListener('load', gameStart, false);
}

We'll also do some extra work in the gameStart function to clear and reinstate the timeout and, since the autofocus attribute gets ignored in onpageshow, focus the input field:

var gameStart = function () {
    window.clearInterval(cdInterval);
    window.clearTimeout(cdTimeout);
    var em = document.getElementById('email');
    var cd = document.getElementById('countdown');
    var sc = document.getElementById('score');
	cd.value = 10;
	sc.value = 0;
	em.value = '';
    em.readOnly = false;
    cdInterval = window.setInterval(counter,1000, cd, sc, em);
    cdTimeout = window.setTimeout(gameOver,10000, cd, sc, em);
    em.focus();
}

Missing from the first version of the game is any way to restart or replay. Let's start off by adding a reset button to the form:

<input id="restart" type="reset" value="New Game">

There are some obvious issues with this, not least that the form reset isn't going to remove the countdown and game over timeouts. However, rather than deal with that by hooking the event in a sensible way, we're going to take this opportunity to investigate an interesting feature of the output element, the defaultValue.

If you try clicking the reset button as it stands, this is what happens to the two output elements:

Picture of the two output elements after a form reset

The output element is something of a hybrid. Although it can be created, declaratively, in markup, it isn't really any use without JavaScript. While not a direct consequence of this state of affairs, it therefore doesn't matter that there's no way to set the default value of an output element in the HTML, you have to do it with JavaScript using the defaultValue property in the DOM. Let's add a function to set up these fields correctly which will be run onload:

var gameSetup = function() {
    document.getElementById('countdown').defaultValue = "10";
    document.getElementById('score').defaultValue = "0";
    document.getElementById('restart').addEventListener('click', gameStart, false);
}

You'll note that there's also an onclick handler added to the button to restart the game. The reason we don't want to capture the form reset event itself is that we're going to use the form reset method within gameStart. These three lines of code:

cd.value = 10;
sc.value = 0;
em.value = '';

Will become this one line of code:

document.getElementById('game').reset();

But now resetting the form will restore the output fields to their defaultValue, as can been seen in the second checkpoint:

Picture of the two output elements after a form reset now that they have defaultValue set

For the third iteration we're going to concentrate on user feedback. This is going to involve both HTML5 and CSS3:

  • Using the onforminput event to update the score immediately
  • Giving instant feedback on the current validity of the email with CSS3

So far feedback to the user happens every second, in the counter function. Instead of updating the the score every second let's update it every time the input changes. There are a number of options in HTML4 already for handling this - we could attach an event to the email field and monitor it for changes, however HTML5 (for now) presents us with another option: onforminput. Instead of being associated with the input field, the item being updated, onforminput can be associated with the output element, the item we want to update:

document.getElementById('score').addEventListener('forminput', updateScore, false);

Because the output element is the target, the update score function looks like this:

var updateScore = function(ev) {
    ev.target.value = calcScore(document.getElementById('email').value);
}

Unfortunately it seems that onforminput may be dropped from HTML5, so we'd better check for support and fall back to capturing any oninput event on the whole form through event bubbling:

if (isEventSupported('forminput')) {
    document.getElementById('score').addEventListener('forminput', updateScore, false);
} else {
    document.getElementById('game').addEventListener('input', updateGlobalScore, false);
}

This does complicate the function to update the score as the target of the event is no longer the output element, it's whatever input element has been updated. At least in our simple case there's only one input element so we can use the ev.target shortcut, just on the other side of the assignment:

var updateGlobalScore = function(ev) {
    document.getElementById('score').value = calcScore(ev.target.value);
}

If you've been following along in Firefox you will have seen that both provide some default styling for invalid fields:

Default invalid field in Firefox

However Chrome (top) and Opera (bottom) don't show any indication:

default invalid field in Chrome

Default invalid field in Opera

Let's apply some styles explicitly to make everything consistent across browsers:

input[type=email]:invalid {
    box-shadow: none;
    background-color: rgba(255,0,0,0.5);
}
input[type=email]:valid {
    box-shadow: none;
    background-color: rgba(0,255,0,0.5);
}

The box-shadow overrides the Firefox default, while the background-color will be applied in all three browsers, as you can see in the third checkpoint.

The game is now functionally complete, but before we wrap this up I'd like to use one further iteration to examine the checkValidity method more closely. Here's what the spec says about checkValidity:

Returns true if the element's value has no validity problems; false otherwise. Fires an invalid event at the element in the latter case.

We only perform additional work so, instead of using the boolean return value of the function to guide or logic, we could make the end of the game event driven. First we'll simplify the gameOver function, as all we need to do there now is ensure the event gets triggered if the email is invalid (and, thanks to onforminput, we know the score will always be up to date):

var gameOver = function (cd, sc, em) {
    window.clearInterval(cdInterval);
    cd.value = 0;
    em.checkValidity();
}

Now we need to declare an function to handle the oninvalidevent, I've chosen to name it in tribute to cheesy European rock:

var theFinalCountdown = function(e) {
    document.getElementById('score').value = 0;
    window.alert("You lose!");
    e.target.readOnly = true;
}

Then we attach it to the oninvalid of the email field:

document.getElementById('email').addEventListener('invalid', theFinalCountdown, false);

Thus concludes my slightly erratic tour through HTML5 form features with the final checkpoint. If you've enjoyed this please check out the more extensive introduction to HTML5 Forms in Chapter 3 of my book.


Tweet this!
Send feedback »PermalinkPermalink

15/11/10

11:22:02 pm Permalink Hello! HTML5 and CSS3 - 50% Off Until 16th December

Categories: Front End Web Development, Standards, HTML and CSS

Buy early access to my book Hello! HTML5 and CSS3 and get a 50% discount for the next month with the code html550. Coming soon will be the chapter on HTML5 Forms, which should be pretty useful for getting up to speed in time for the release of Firefox 4.


Tweet this!
Send feedback »PermalinkPermalink

30/06/10

11:21:02 pm Permalink Attempting Better Drop Shadows in IE8 - Filters Revisited

Categories: Front End Web Development

I was reading about cssSandpaper today and my curiosity was sparked by this line:

Note that in IE, the blur-radius is not currently not supported, due to a lack of support in IE?s DropShadow filter.

This is true, DropShadow doesn't support blur radius. The alternative Shadow filter does have a blur radius like property, Strength, which "Sets or retrieves the distance, in pixels, that a filter effect extends."

Example of both the DropShadow and Shadow filter in action

So there are two basic options, both with their own advantages and disadvantages:

  • DropShadow - you can use alpha transparent colours and specify separate offsets, but the colour remains solid and sharp edged
  • Shadow - you can specify a blur radius type property but you cannot set separate x and y offsets, the colour will fade to transparent but you have no control over it, and the results also remain solid and sharp edged

Basically, drop shadows in IE look like they were designed by developers rather than graphic designers, see for yourself in the example to the right - top is DropShadow, bottom is Shadow, hard edges in both cases.

Many, like myself, have taken the position that this can't be helped, we should be grateful to be able to do drop shadows at all in CSS for IE, and just picked one of the two options and got on with things. However, at least in IE8, there may be some further options which are worth investigating. The following text is on every MSDN filter page:

You can assign multiple filters or transitions to an object by declaring each in the filter property of the object.

And guess what? There is a Blur filter and, if that turns out to be no good, there's also a MotionBlur and a Glow which we may be able to do something with. So my strategy in this post is to apply some of these in combination with DropShadow and Shadow to see if we can get slightly more natural looking CSS drop shadows in Internet Explorer. First, lets remind ourselves what an IE drop shadow looks like:

DropShadow by itself

And here's the code:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.DropShadow(OffX=6, OffY=4, Color='gray')
    ">Straight drop shadow example</div>

Let's try adding a blur to that and see what happens:

DropShadow and blur in combination

As you can see, the blur effect applies to the shadow but it also applies to the contents.

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.DropShadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        0 Example text, should not have shadow or be blurred.</div>

I wondered if I could wrap the contents in another element and protect it somehow from the filter.

DropShadow and blur in combination, text in a child element

A shadow on an element with a transparent background will produce a text shadow, while a background colour will cause the shadow to apply to the box. So I thought it was worth a try, and I thought I'd trigger hasLayout to be on the safe side:

<div style="height: 30px; filter:
    progid:DXImageTransform.Microsoft.DropShadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        <span style="height: 30px; zoom:1; background-color: #fff;">
            1 Example text, should not have shadow or be blurred.</span></div>

Not much joy there, but I did have a bit better luck with the next attempt:

DropShadow and blur in combination, text in absolutely positioned element

By making the child element absolutely positioned the filters were now ignored on the containing element, of course the containing element is now empty so needs an explicit height to keep it open:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.DropShadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        <span style="position: absolute; height: 30px; zoom:1; background-color: #fff;">
            2 Example text, should not have shadow or be blurred.</span></div>

The problem is that the span now pokes out of the containing div, so I tried fitting it more exactly:

DropShadow and Blur in combination, text in offset absolutely positioned element

Quite a lot of additional markup is now getting tacked on, for really not much aesthetic benefit. Having the absolutely positioned child match the dimensions of the containing div does mean that you can cover up the blurry top and left edges, but the tradeoff is the elements need to have known dimensions.:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.DropShadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        <span style="position: absolute; top: 2px; left: 2px; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            3 Example text, should not have shadow or be blurred.</span></div>

Since the shadow still looks crappy I thought I'd try a few different combinations. Motion blur:

DropShadow and Motion Blur in combination, text in absolutely positioned element

And the code:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.MotionBlur(direction=135,strength=8,add=true)">
        <span style="position: absolute; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            4 Example text, should not have shadow or be blurred.</span></div>

Glow:

DropShadow and Glow in combination, text in absolutely positioned element

More code:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=6, OffY=4, Color='gray')
    progid:DXImageTransform.Microsoft.Glow(strength=2,Color='gray')">
        <span style="position: absolute; top: 1px; left: 1px; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            5 Example text, should not have shadow or be blurred.</span></div>

What about just applying multiple drop shadows?

Multiple alpha transparent DropShadows

The above image combines four:

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#cc999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#99999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#66999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#33999999)">
        <span style="position: absolute; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            6 Example text, should not have shadow or be blurred.</span></div>

Getting a bit far out now, multiple drop shadows and blur:

Multiple DropShadows with Blur

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#cc999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#99999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#66999999)
    progid:DXImageTransform.Microsoft.Dropshadow(OffX=4, OffY=4, Color=#33999999)
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        <span style="position: absolute; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            7 Example text, should not have shadow or be blurred.</span></div>

Enough of that, I thought I'd try a few examples with shadow instead of drop shadow:

Shadow by itself

The basic shadow fades out but, as I mentioned, is sharp edged.

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Shadow(Direction=135, Strength=5, Color='gray')">
        Straight shadow example</div>

Now a shadow with a blur:

Shadow by itself

<div style="position: relative; height: 30px; filter:
    progid:DXImageTransform.Microsoft.Shadow(Direction=135, Strength=5, Color='gray')
    progid:DXImageTransform.Microsoft.Blur(pixelradius=2)">
        <span style="position: absolute; top: 2px; left: 2px; height: 30px; width: 100%; display: inline-block; background-color: #fff;">
            3 Example text, should not have shadow or be blurred.</span></div>

A shadow with motion blur:

Shadow with Motion Blur

And with glow:

Shadow with Glow

Yes, they all still look a bit pants.

So it seems like Shadow and Blur in combination may be the best of a bad bunch, and they don't really give you too many advantages: you have to know the dimensions of the element in advance for it to be useful in CSS; you might be able to work a jQuery plugin out of it, but if you're going to rely on scripting you might as well make use of once the image based solutions which result in nicer looking shadows; and finally, all of the above only works in IE8 - IE7 applies all the filters to the contained element whether it's positioned or not. So, wasted effort? Possibly, at least now I know for sure, here's hoping IE9 adds support for box-shadow &amp;#58;&amp;#41;


Tweet this!
Send feedback »PermalinkPermalink

03/04/10

10:11:26 pm Permalink London Web Standards: Javascript with Frances Berriman and Jake Archibald

Categories: Front End Web Development, Management and Communication

Review: LWS March: JavaScript ? The events that get left behind & Pro-bunfighting at The Square Pig, 30 - 32 Procter Street, Holborn, London, WC1V 6NX 19:00 to 20:30

This event was focussed on JavaScript, specifically the Glow 2 library from the BBC which both speakers are working on. Frances talked about coordinating work on a JavaScript project with a geographically distributed team, discussing some teamwork strategies and demonstrating some useful tools. Jake talked about the nightmare that is DOM Level 2 keyboard events and how he'd worked around the issues in Glow 2. Both of them were funny and engaging speakers, so much so that I feel I could hardly do them justice with a textual repetition of their talks. That and I didn't really take detailed notes this time, and had to leave before the Q&A... So, for a summary of what was said check out the usual live blog of the event from Jeff, meanwhile I'm going to have a play around with three of the JavaScript tools discussed: JSDoc, QUnit and Glow 2 keyboard events.

JSDoc

In team environments developers are supposed to liberally comment their code and also document the requirements before coding, and the APIs afterwards. Inevitably anything that developers are asked to do which is not strictly coding tends to take a back seat, especially when deadlines are approaching. Documentation requirements therefore get skimped or skipped, and often are not kept in sync as the code evolves. In the Enterprise development world this issue led to the development of tools like JavaDoc which, if you write your comments in a particular format, will automatically generate nicely formatted documentation for you when you've finished. This halves the amount of documentation you have to write, increasing the chance developers will do it, and keeps that documentation close to the source code to which it pertains, improving the chance it's kept up to date. JavaDoc has been much imitated, and the JavaScript equivalent is JSDoc.

So, how do you use JSDoc? First you have to download and extract the latest version, you also need to have a Java runtime installed, version 1.5 or later. Now you have to adjust your comments slightly, assuming you have comments in your code already &amp;#58;&amp;#41; I didn't, so I grabbed the complex.js file I'd copied out of the rhino book for my post on the canvas element. You can run JSDoc on that file as it stands and it will generate some documentation. Assuming you're in a command prompt in the directory where you extracted JSDoc (and, er, you're on Linux - adjust path separators if you're on Windows), issue a command line like this:

java -jar jsrun.jar app/run.js -a -t=templates/jsdoc/ ../code/complex.js

The command will produce a directory out with the generated documentation. This is what the basic documentation looks like:

The results of JSDoc on a standard JavaScript file

As you can see (check out the full results), it's found the constructor function but not much else - everything is in the global namespace. Let's annotate the comment before the constructor function and see what happens, this is what it looked like before:

/*
 * The first step in defining a class is defining the constructor
And here's what it looks like when it's JSDoc enabled:
/**
 * The first step in defining a class is defining the constructor
Can you see the difference? Look closely at the first line - there's one extra asterisk. That extra asterisk is what tells JSDoc to look in this comment for 'special' stuff. At the end of the comment I'm going to add an annotation:
 * @constructor
 */

Run the command again and suddenly there's a whole load more stuff:

The results of JSDoc on a JavaScript file with a single annotation

In the new version of the documentation there's a Complex class, and it's found all the methods. However, your fellow coders may appreciate a bit more than the basics. Perhaps you might want to document what the expected parameters and return values are? Additional annotations follow the same pattern as @constructor - an ampersand followed by a keyword. Some of the other keywords let you provide additional information, here's what parameters and return values look like:

/**
 *Add two complex numbers and return the result.
 *@param a {Complex} A complex number
 *@param b {Complex} A second complex number
 *@returns {Complex} The sum of a and b
 */

Now JSDoc adds your comments to the output, and additionally provides links to any other types you've defined:

The results of JSDoc on a JavaScript file with several annotations

You can have a look at the final output here.

QUnit

Unit testing is something I keep thinking I should learn how to do. The BBC Glow team is using the jQuery unit testing framework QUnit, so this seems like a good excuse to investigate it.

QUnit is very easy to set up, you just need to link to JQuery and the two QUnit files in your document head:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
Then provide some HTML framework for the results to appear in:
<h1 id="qunit-header">QUnit example</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
Now you need to write some tests. To do this, simply add a function to $(document).ready that calls the test function:
test("Passing tests", function() {
  ok(true, "The truth is true");
  equals(1,1, "One is one");
});

These are obviously quite basic tests, and not actually testing anything, but demonstrate how easy it is. The ok test accepts a 'truthy' value and a string and succeeds if the value is true, the equals test accepts two values and a string and succeeds if they're equal.

Basic QUnit tests

To try some less basic tests I once again dragged out the complex.js file. The test functions can contain more than just the testing functions, you can put as much JavaScript in there as you need to do your test. Here's what I ended up with:

test("Basic class functionality", function() {
  expect(4);
  var real = 1.0;
  var imaginary = 1.0;
  var c;
  ok( c = new Complex(real,imaginary), "Class created" );
  equals( c, real, "Simple value comparison" );
  equals( c.toString(), "{" + real + "," + imaginary + "}", "String comparison");
  equals( c.magnitude(), Math.sqrt(2.0), "Magnitude comparison")
});

You can see I've used the ok test to confirm the object gets created, then done some simple comparisons to make sure the object created is what I expect. Unsurprisingly, all my tests pass:

Slightly less basic QUnit tests

Of course, this just demonstrates that QUnit is very straightforward to use rather than that some code I nicked out of a book works perfectly. There's a whole art to writing unit tests over and above the simple mechanics of the framework you're using, but I'm definitely not the person to be telling you about that. If anyone knows of any good, JS oriented tutorials for doing test driven development, please leave a comment.

Glow 2 Keyboard Events

Jake talked about the mess that is keyboard events in current browsers, and how he set about fixing it in Glow 2. The problem with keyboard events in browsers can be summed up by a quick look at the W3C DOM Level 2 Spec:

A visual comparison of the size of the mouse event spec with the much shorter keyboard event spec

Given the lack of spec it's hardly surprising that the browsers have all implemented keyboard events slightly differently. Not only have the browser implemented things differently from each other, there are also differences between the same browsers on different operating systems. Throw in the fact that keyboards in different countries have different sets of keys, and it all gets a bit messy. In Glow 2, the keyboard events have been normalised to keydown, keyup and keypress, with the same properties on the event object across browsers.

I've downloaded the Glow 2 source to have a go with these keyboard events. After downloading the extra libraries I've managed to get it to build with Ant, but I've not got the build itself working in a browser yet. It could be me, it could be a bug, I haven't figured it out yet - when I do I'll fix up my keyboard event example application and update this post.

Another excellent event, the two best speakers of the three events I've been to, 5 out of 5. Watch out for the next one on 26th April.

Technorati tags for this review:  

Tweet this!
1 feedback »PermalinkPermalink