Archive for the ‘javascript/css’ Category

When using canvas, make sure you set the width and height explicitly

Friday, August 27th, 2010

According to this explanation on stackoverflow, it appears that if you set the width and height of your canvas element in css

canvas {

    height: 20px;
    width: 20px;

}

whenever you render vectors on the canvas they will appear stretched as css only sets the container size not the canvas size. So you have to do something like this:


    var canvas = document.getElementById("canvas");
    canvas.setAttribute("width", "20);
    canvas.setAttribute("height", "20);

How. Strange.

Where to put your CSS hacks - conditioning your conditionals.

Wednesday, March 3rd, 2010

I’ve had/heard/seen this argument many times on blog after blog. So I thought it would be a useful blog post to highlight to upsides and down sides to each argument.

Conditional Comments

Conditional commenting is the practice of putting code in special comments in your HTML document that get executed only in specified IE browers, it usually looks something like this:

conditionalcommment
  • Pro’s

  • Keeps hacks separate making style sheet look clean.
  • Allows for automated validation of main style sheet
  • Enables clean easy use of completely browser specific enhancement code like filters and expressions
  • Is backwards compatible
  • Con’s

  • Encourages people to write browser specific CSS instead of writing better CSS. (broken windows theory)
  • Decoupling of styles can result in more bugs when people forget to update the conditional stylesheet. Also bugs can be harder to track down.
  • Is an extra HTTP request

Inline CSS Hacks

Inline CSS hacks are where you write *hacked* attribute, property pairs in your CSS using combinations of ascii characters to take advantage of bugs in different CSS parsers, looking something like this:

inlinehacks
  • Pro’s

  • Keeps hacks together with real code for easier tracing/debugging.
  • Less likely duplication of code
  • Con’s

  • Encourages people to use hacks instead of writing better CSS. (broken windows theory)
  • Stops automated validation of CSS as hacks are in the core code.
  • Hacks can be unreliable and have adverse effects on different browsers other than the infamously un-robust IE family.
  • Is not backwards compatible, if a hack gets fixed the rendering will break on later browsers

Ultimately it’s a preference thing and you can spin these pro’s and con’s either way to support your chosen method of development, but once it’s been chosen all developers need to stick with it. I think the important thing is that everyone needs to be vigilant that both are used with extreme caution and care as a last last resort in the CSS.

I see two useful things that could be created to follow this up to create the desired behaviour:

  • setting up some code that analyses the amount of CSS versus the amount of hacks or conditionals, then having a theoretical limit say 5% that you are not allowed to go above for a successful build.
  • Having a rule to write a detailed reasoned 3 line discourse in comments giving a description of why and in what circumstance each hacked rule is required.

Personally I opt of the conditional method, but that’s because I have a bizarre obsession with automated validation of CSS. See CSSOrder.

Cleaning up production code with JSLint. Once and for all.

Tuesday, November 24th, 2009

Sit back. Close your eyes. Imagine the scene.

Your client is sat round a big 3 inch thick mahogany table, in a tastefully decorated 1930’s art deco hotel conference room. They lean back in their reclining leather chairs whilst sipping chilled Harrods mineral water served in crystal wine glasses. The leather creaks. The sun pierces the cloud glinting through the gaps in the blinds filling the room with a coruscating light, a dazzlingly you are praying to match in the events that follow. Formalities are exchanged and weather is discussed. A thin veil of cultural formality gives you a brief respite from the reason you all know you are there.

You tap the mouse connected to the macbook. The projector flickers into life. The first page of your masterpiece is lit up. Each pixel a glorious testament to your craftsmanship and the pain, sweat and blood you’ve slaved over for the past iteration. Each click though the journey provides the perfect accompaniment to your commentary, going deep and deeper into your world, building a crescendo around it that signifies your masterful control of your media. Click follows click. Ouuu follows ahhh. And then…

Bang!

alert

Has this or something along similar lines ever happened to you before?

Your heart sinks. Your face burns as the blood rushes like a stampede of elephants into your cheeks. You blush. You stutter a laugh. Make a self deprecating witticism about the realities of live demos. You click ok. You proceed with the demo. Inside you are crying tears of shame and remorse. “Why didn’t I catch that before?” you think.

Which, by the way, is wrong.

If you had more time to think about the question you should have actually asked is “why did that happen at all?”. To which the answer would have been, it shouldn’t.

Debug code, should never make it into the production environment. It’s just bad practice. Plain and simple. So the question becomes, “how do we stop it?”.

On my latest project I’ve been working with CI or Continuous Integration. I won’t go into the details of how CI works, you can find that out yourself.

As part of this, I’ve been using 3 very important tools: Maven, JSLint4Java and JSLint itself.

Maven is a build tool that allows me to add the marvellous JSLint4Java ant plugin to it. This means when Maven is triggered by the CI system, JSLint gets run on all the Javascript and CSS files in my project. If they fail the validation: the build fails. Simple as that.

console

Now, this gives us a lot power, to help both enforce code consistency, valid code and good code.

But up until recently, JSLint has not had the functionality to check for the javascript global alerts, consoles, debug or opera statements. But as of 19th of November 2009, after suggesting a console check, on the JSLint working group forum. The ability to be able to check for the globals: console, alert, Opera, prompt and debug have been added to JSLint by programming/Javascript legend Douglas Crockford himself.

AWESOME.

The new functionality comes under the ASSUME keyword, that when you switch off using the following code:

/*devel : false, debug : false */

will fail the file if any of those statements are present in the code…

This brings us one step closer to the holy grail of front end code RELIABILITY and eradicates the scenario I wrote about at the beginning of the post. But still doesn’t completely protect you from looking like an idiot in front of the client, so take care!

Coders block

Wednesday, November 18th, 2009

Sometimes trying to code can be like standing on the edge of an abyss.

abyss_ver3

You desperately want to take that leap off the firm, solid edge of reason and safety into the infinitely consuming unknown world of possibility that awaits you. But for all your heart, passion and fire, your brain is resolutely locked, frozen in place, destined to stare longingly out of your cold dead eyes at the wonders that could have been.

Your fingers tense as you try to force line after painful line of code from them. With each line you see another 3 lines that you should delete from earlier in the forcing process.

Each decisions you make is an excruciating process of taking a thousand different possibilities whittling them down and then taking a random guess that it’s the correct course of action. With each character you type your struck by the heinous unreusability of what your creating and that your never going to be able to get back to the pure zen state of a blank page that your soiling at this very moment.

You close your eyes and everyone who has ever condemned you as a failure, mocked your ability, or questioned any sense of validity as a human being is stood in a large circle pointing and riotously laughing at you.

This, this my friends is the hell of coders block.

A crippling affliction akin to the crushing sensation you get as a man when you fail to perform sexually, or the soul crushing moment at school where you are picked last for a sports team due to uncoordinated inability. One of those moments in life where you literally question the entire worth of your existence and pose the question “should I go on?”.

Well, maybe not quite that bad. But pretty damn close.

Today, I have failed to be at all productive. Infected by this disease of the mind, I have sat trying to code for 8 hours but achieving nothing more than responding to emails, reading blogs, writing blogs feeding my lethargic, flu infested body, festering in the social underbelly of mankind.

I even googled, coders block to avoid actually having to write any code! This is not a good day. The sooner it ends, the better…

All hands : abandon scrollbars!

Wednesday, November 4th, 2009

I’ve had to do a lot of things in my career as an interaction developer that I’ve despised.

A favourite bug bear of mine is having to reimplement standard browser controls in JavaScript. The familiar tale of the powers that be deciding they want to create custom designs for every tiny part of the web interface. Inevitably as the code monkey it’s your job to take it up the rear and produce these gems no matter how hard, annoying or pointless they are until someone, somewhere, can climax into a design ejaculation, probably whilst flicking through the centrefolds of a Taschen Philippe Starck product book. No wonder when you pick them up in Waterstones they are always sticky…

One of the repeat offenders of this list is the poor old scroll bar. Admittedly a tad ugly looking in some OS’s but never the less a stalwart of interaction design. The number of times I have been asked to re-implement this, using a variety of different colours, shapes, sizes has grown too long to count. I’ve spent a lot of time agonizing/swearing over scrollbar engineering principles and now it’s my turn to implement the scrollbars I want.

Now the scrollbars I want.

Are invisible.

I can’t remember when I watched it, but many moons ago, I came across Edward Tufte’s excellent dissection of the iPhone’s interface. The idea that really resonated with me on this, was the concept of eradicating “administrative debris”, controls that were just there to control, things that could be re-implemented to be intuitive behaviors, without the need for a reserved space of visual feedback that clutters and constricts the screen real estate. A beautiful example of this is how the iPhone, does away with scrollbars, in favour of a tactile drag/swipe scroll mechanism.

iphone

So, I thought, why not put the inane knowledge I have of JavaScript and the browser scrolling api to use, and implement a version of the iphone scroller, in a jQuery Plugin.

Six months later, someone else has beaten me to the punch.

There is already an jQuery iPhone scroller plugin, which is annoying as I produced the POC over six months ago, but only recently got around to tidying it up and refactoring it. BALLS. Oh well such is life. Anyway, mine needs some work, but is generally better.

Some examples are below:

Vertical Scroller

The iPhone platform elegantly solves the design problem of small screens by greatly intensifying the information resolution of each displayed page. Small screens, as on traditional cell phones, show very little information per screen, which in turn leads to deep hierarchies of stacked-up thin information–too often leaving users with “Where am I?” puzzles. Better to have users looking over material adjacent in space rather than stacked in time.

To do so requires increasing the information resolution of the screen by the hardware (higher resolution screens) and by screen design (eliminating screen-hogging computer administrative debris, and distributing information adjacent in space).

This video shows some of the resolution-enhancing methods of the iPhone, along with a few places for improvements in resolution.

In 1994-1995 I designed (while consulting for IBM) screen mock-ups for navigating through the National Gallery via information kiosks. (The National Gallery had the good sense not to adopt the proposal.) For several years these screen designs were handouts in the one-day course in my discussion of interface design, and were then published in my book Visual Explanations (1997).

The design ideas here include high-resolution touch-screens; minimizing computer admin debris; spatial distribution of information rather than temporal stacking; complete integration of text, images, and live video; a flat non-hierarchical interface; and replacing spacious icons with tight words. The metaphor for the interface is the information. Thus the iPhone got it mostly right.

Another critique of the current weather application (one that I believe can be rectified once the SDK comes out in February): more detail is difficult to obtain. For instance, most standard weather displays (TV, newspaper, etc.) give the chance of precipitation and the humidity level. This information could easily fit on the weather screen, but it isn’t there. If I click on the Y! logo at the bottom left, it takes me to a Yahoo mobile page that shows ads and no additional details about the weather (plenty of other random info about my area though…).

Quisque sem diam, ullamcorper et, volutpat et, dignissim sit amet, ligula. Praesent accumsan justo vitae metus. Nunc pretium aliquet libero. Nulla ut pede et lectus iaculis accumsan. Nulla aliquet arcu at quam. Pellentesque cursus adipiscing dolor. Suspendisse volutpat magna id nisi. Ut pretium nisi in elit. Curabitur id arcu. Maecenas eu quam. Curabitur ultricies, lectus quis commodo dignissim, felis turpis vehicula arcu, ac faucibus risus metus vitae turpis. Maecenas et lacus ut enim vulputate interdum. Mauris ut diam ut urna laoreet tristique. Aenean malesuada consectetur erat.

Phasellus eleifend, velit at semper fringilla, metus dolor hendrerit dui, id consequat enim purus vitae est. Sed tristique. Quisque hendrerit ullamcorper tortor. Vivamus pretium fringilla lacus. Maecenas in mi quis lorem auctor egestas. Vivamus quis urna dapibus sem euismod congue. In hac habitasse platea dictumst. Mauris metus sem, molestie in, tristique non, pellentesque a, enim. Aenean eleifend urna sit amet libero. Cras in diam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla porttitor pharetra quam. Cras ac massa in nisi semper rutrum. Aliquam at tellus. Morbi tincidunt.

Horizontal Scroller

The iPhone platform elegantly solves the design problem of small screens by greatly intensifying the information resolution of each displayed page. Small screens, as on traditional cell phones, show very little information per screen, which in turn leads to deep hierarchies of stacked-up thin information–too often leaving users with “Where am I?” puzzles. Better to have users looking over material adjacent in space rather than stacked in time.

To do so requires increasing the information resolution of the screen by the hardware (higher resolution screens) and by screen design (eliminating screen-hogging computer administrative debris, and distributing information adjacent in space).

This video shows some of the resolution-enhancing methods of the iPhone, along with a few places for improvements in resolution.

In 1994-1995 I designed (while consulting for IBM) screen mock-ups for navigating through the National Gallery via information kiosks. (The National Gallery had the good sense not to adopt the proposal.) For several years these screen designs were handouts in the one-day course in my discussion of interface design, and were then published in my book Visual Explanations (1997).

The design ideas here include high-resolution touch-screens; minimizing computer admin debris; spatial distribution of information rather than temporal stacking; complete integration of text, images, and live video; a flat non-hierarchical interface; and replacing spacious icons with tight words. The metaphor for the interface is the information. Thus the iPhone got it mostly right.

Another critique of the current weather application (one that I believe can be rectified once the SDK comes out in February): more detail is difficult to obtain. For instance, most standard weather displays (TV, newspaper, etc.) give the chance of precipitation and the humidity level. This information could easily fit on the weather screen, but it isn’t there. If I click on the Y! logo at the bottom left, it takes me to a Yahoo mobile page that shows ads and no additional details about the weather (plenty of other random info about my area though…).

Quisque sem diam, ullamcorper et, volutpat et, dignissim sit amet, ligula. Praesent accumsan justo vitae metus. Nunc pretium aliquet libero. Nulla ut pede et lectus iaculis accumsan. Nulla aliquet arcu at quam. Pellentesque cursus adipiscing dolor. Suspendisse volutpat magna id nisi. Ut pretium nisi in elit. Curabitur id arcu. Maecenas eu quam. Curabitur ultricies, lectus quis commodo dignissim, felis turpis vehicula arcu, ac faucibus risus metus vitae turpis. Maecenas et lacus ut enim vulputate interdum. Mauris ut diam ut urna laoreet tristique. Aenean malesuada consectetur erat.

Phasellus eleifend, velit at semper fringilla, metus dolor hendrerit dui, id consequat enim purus vitae est. Sed tristique. Quisque hendrerit ullamcorper tortor. Vivamus pretium fringilla lacus. Maecenas in mi quis lorem auctor egestas. Vivamus quis urna dapibus sem euismod congue. In hac habitasse platea dictumst. Mauris metus sem, molestie in, tristique non, pellentesque a, enim. Aenean eleifend urna sit amet libero. Cras in diam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla porttitor pharetra quam. Cras ac massa in nisi semper rutrum. Aliquam at tellus. Morbi tincidunt.

In hac habitasse platea dictumst. Proin consequat bibendum tortor. Phasellus mollis, lectus non imperdiet ultrices, magna elit fermentum orci, rhoncus varius urna mi at est. Aenean ut velit. Pellentesque velit nunc, ullamcorper vel, iaculis cursus, facilisis non, nisl. Nam pede diam, venenatis sit amet, consequat vel, malesuada quis, enim. Ut adipiscing, turpis pulvinar mattis ultrices, enim mi euismod arcu, in imperdiet nunc nisl id pede. Maecenas non dolor. Nullam mi turpis, hendrerit ut, ultricies id, lacinia sit amet, turpis. Sed accumsan, ipsum at faucibus scelerisque, nisi neque commodo ante, sed tincidunt massa lectus in eros. Sed bibendum turpis scelerisque purus. Pellentesque vitae ipsum. Duis sodales fringilla ante. Pellentesque posuere posuere tellus. Phasellus gravida laoreet risus. Integer vitae felis tincidunt felis vulputate semper. Duis semper sem a pede. Praesent quis lectus vel felis varius feugiat. Phasellus ipsum nulla, auctor eget, euismod at, elementum ac, pede.

Proin venenatis augue sit amet felis hendrerit lacinia. In molestie augue sed arcu. Mauris posuere velit eu leo. Mauris commodo. Aenean lacinia dignissim libero. Curabitur quis enim quis augue interdum facilisis. Integer elementum sem nec lectus. Curabitur rutrum nulla in felis. Morbi mattis turpis id diam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin lectus. Morbi lorem augue, suscipit nec, iaculis eu, tincidunt quis, erat. Duis at ante sit amet dui molestie scelerisque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus sodales, risus eu lobortis posuere, justo turpis laoreet ante, eget aliquet nunc metus in erat. Praesent imperdiet orci. Quisque sapien nulla, interdum quis, viverra vel, varius et, lacus. Proin nec risus a ante egestas dictum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida. Etiam neque lacus, pulvinar a, sollicitudin in, scelerisque suscipit, risus. Vivamus tristique ipsum ac libero. Suspendisse at turpis. Fusce tincidunt, nisi ut porta porta, quam nibh posuere metus, non euismod pede tellus ullamcorper nisi. Praesent dignissim enim consequat odio. Nullam sed velit a arcu volutpat vulputate. Morbi vel est. Vestibulum suscipit nulla blandit libero. Ut aliquam velit in erat. Donec rhoncus ligula quis ante. Morbi fermentum erat in nibh. Suspendisse elit pede, commodo eleifend, faucibus at, eleifend ac, nunc. Phasellus interdum, mauris vitae egestas tempor, ligula sapien vulputate risus, vel placerat tellus ipsum quis tortor. Etiam sodales, tellus eget molestie blandit, metus turpis volutpat arcu, vehicula gravida diam massa vehicula elit. Aliquam id ante. In in ipsum at sapien condimentum varius.

Quisque sem diam, ullamcorper et, volutpat et, dignissim sit amet, ligula. Praesent accumsan justo vitae metus. Nunc pretium aliquet libero. Nulla ut pede et lectus iaculis accumsan. Nulla aliquet arcu at quam. Pellentesque cursus adipiscing dolor. Suspendisse volutpat magna id nisi. Ut pretium nisi in elit. Curabitur id arcu. Maecenas eu quam. Curabitur ultricies, lectus quis commodo dignissim, felis turpis vehicula arcu, ac faucibus risus metus vitae turpis. Maecenas et lacus ut enim vulputate interdum. Mauris ut diam ut urna laoreet tristique. Aenean malesuada consectetur erat.

Phasellus eleifend, velit at semper fringilla, metus dolor hendrerit dui, id consequat enim purus vitae est. Sed tristique. Quisque hendrerit ullamcorper tortor. Vivamus pretium fringilla lacus. Maecenas in mi quis lorem auctor egestas. Vivamus quis urna dapibus sem euismod congue. In hac habitasse platea dictumst. Mauris metus sem, molestie in, tristique non, pellentesque a, enim. Aenean eleifend urna sit amet libero. Cras in diam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla porttitor pharetra quam. Cras ac massa in nisi semper rutrum. Aliquam at tellus. Morbi tincidunt.

In hac habitasse platea dictumst. Proin consequat bibendum tortor. Phasellus mollis, lectus non imperdiet ultrices, magna elit fermentum orci, rhoncus varius urna mi at est. Aenean ut velit. Pellentesque velit nunc, ullamcorper vel, iaculis cursus, facilisis non, nisl. Nam pede diam, venenatis sit amet, consequat vel, malesuada quis, enim. Ut adipiscing, turpis pulvinar mattis ultrices, enim mi euismod arcu, in imperdiet nunc nisl id pede. Maecenas non dolor. Nullam mi turpis, hendrerit ut, ultricies id, lacinia sit amet, turpis. Sed accumsan, ipsum at faucibus scelerisque, nisi neque commodo ante, sed tincidunt massa lectus in eros. Sed bibendum turpis scelerisque purus. Pellentesque vitae ipsum. Duis sodales fringilla ante. Pellentesque posuere posuere tellus. Phasellus gravida laoreet risus. Integer vitae felis tincidunt felis vulputate semper. Duis semper sem a pede. Praesent quis lectus vel felis varius feugiat. Phasellus ipsum nulla, auctor eget, euismod at, elementum ac, pede.

Proin venenatis augue sit amet felis hendrerit lacinia. In molestie augue sed arcu. Mauris posuere velit eu leo. Mauris commodo. Aenean lacinia dignissim libero. Curabitur quis enim quis augue interdum facilisis. Integer elementum sem nec lectus. Curabitur rutrum nulla in felis. Morbi mattis turpis id diam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin lectus. Morbi lorem augue, suscipit nec, iaculis eu, tincidunt quis, erat. Duis at ante sit amet dui molestie scelerisque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus sodales, risus eu lobortis posuere, justo turpis laoreet ante, eget aliquet nunc metus in erat. Praesent imperdiet orci. Quisque sapien nulla, interdum quis, viverra vel, varius et, lacus. Proin nec risus a ante egestas dictum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida. Etiam neque lacus, pulvinar a, sollicitudin in, scelerisque suscipit, risus. Vivamus tristique ipsum ac libero. Suspendisse at turpis. Fusce tincidunt, nisi ut porta porta, quam nibh posuere metus, non euismod pede tellus ullamcorper nisi. Praesent dignissim enim consequat odio. Nullam sed velit a arcu volutpat vulputate. Morbi vel est. Vestibulum suscipit nulla blandit libero. Ut aliquam velit in erat. Donec rhoncus ligula quis ante. Morbi fermentum erat in nibh. Suspendisse elit pede, commodo eleifend, faucibus at, eleifend ac, nunc. Phasellus interdum, mauris vitae egestas tempor, ligula sapien vulputate risus, vel placerat tellus ipsum quis tortor. Etiam sodales, tellus eget molestie blandit, metus turpis volutpat arcu, vehicula gravida diam massa vehicula elit. Aliquam id ante. In in ipsum at sapien condimentum varius.

Quisque sem diam, ullamcorper et, volutpat et, dignissim sit amet, ligula. Praesent accumsan justo vitae metus. Nunc pretium aliquet libero. Nulla ut pede et lectus iaculis accumsan. Nulla aliquet arcu at quam. Pellentesque cursus adipiscing dolor. Suspendisse volutpat magna id nisi. Ut pretium nisi in elit. Curabitur id arcu. Maecenas eu quam. Curabitur ultricies, lectus quis commodo dignissim, felis turpis vehicula arcu, ac faucibus risus metus vitae turpis. Maecenas et lacus ut enim vulputate interdum. Mauris ut diam ut urna laoreet tristique. Aenean malesuada consectetur erat.

Phasellus eleifend, velit at semper fringilla, metus dolor hendrerit dui, id consequat enim purus vitae est. Sed tristique. Quisque hendrerit ullamcorper tortor. Vivamus pretium fringilla lacus. Maecenas in mi quis lorem auctor egestas. Vivamus quis urna dapibus sem euismod congue. In hac habitasse platea dictumst. Mauris metus sem, molestie in, tristique non, pellentesque a, enim. Aenean eleifend urna sit amet libero. Cras in diam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla porttitor pharetra quam. Cras ac massa in nisi semper rutrum. Aliquam at tellus. Morbi tincidunt.

In hac habitasse platea dictumst. Proin consequat bibendum tortor. Phasellus mollis, lectus non imperdiet ultrices, magna elit fermentum orci, rhoncus varius urna mi at est. Aenean ut velit. Pellentesque velit nunc, ullamcorper vel, iaculis cursus, facilisis non, nisl. Nam pede diam, venenatis sit amet, consequat vel, malesuada quis, enim. Ut adipiscing, turpis pulvinar mattis ultrices, enim mi euismod arcu, in imperdiet nunc nisl id pede. Maecenas non dolor. Nullam mi turpis, hendrerit ut, ultricies id, lacinia sit amet, turpis. Sed accumsan, ipsum at faucibus scelerisque, nisi neque commodo ante, sed tincidunt massa lectus in eros. Sed bibendum turpis scelerisque purus. Pellentesque vitae ipsum. Duis sodales fringilla ante. Pellentesque posuere posuere tellus. Phasellus gravida laoreet risus. Integer vitae felis tincidunt felis vulputate semper. Duis semper sem a pede. Praesent quis lectus vel felis varius feugiat. Phasellus ipsum nulla, auctor eget, euismod at, elementum ac, pede.

Proin venenatis augue sit amet felis hendrerit lacinia. In molestie augue sed arcu. Mauris posuere velit eu leo. Mauris commodo. Aenean lacinia dignissim libero. Curabitur quis enim quis augue interdum facilisis. Integer elementum sem nec lectus. Curabitur rutrum nulla in felis. Morbi mattis turpis id diam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin lectus. Morbi lorem augue, suscipit nec, iaculis eu, tincidunt quis, erat. Duis at ante sit amet dui molestie scelerisque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus sodales, risus eu lobortis posuere, justo turpis laoreet ante, eget aliquet nunc metus in erat. Praesent imperdiet orci. Quisque sapien nulla, interdum quis, viverra vel, varius et, lacus. Proin nec risus a ante egestas dictum.

CSSUnit : experimenting with unit testing presentation code.

Thursday, October 1st, 2009

Not all developers are created equal.

In a perfect world, everyone would be super diligent and proficient at creating CSS, but in reality this is not the case. In some cases less experienced developers can make mistakes, create inconsistant code or not reuse exiting code. Even in other cases when more than one experienced developer works on a project, you can still end up with inconsistency and repeated code just by the dint of different working styles.

cssunitscreenshotI thought I’d start experimenting with automated testing of frontend presentation code, focussing on regression testing. This topic is not really discussed a lot, as the standard response is that there is no replacement for an eyeball test, but humans are by nature unreliable beasts and I’d like to change that and make front-end more of an accepted science.

My hope is that by trying out some techniques and bringing them into the forum I can at least start a discussion that results in an advancement of this field. Allowing us to escape some of the common traps we see at the moment and mitigate some of the risks associated with our profession in the same way back end coding has with unit testing.

Existing approaches

This is by no means the first time anyone has looked at this problem. There are other software solutions available like Hp’s WinRunner, but in my opinion they are generally unsuccessful or not fit for purpose. The existing solutions rely on doing algorithmic pixel-based comparisons of screens. Of which the process involves, a screen being designed & built. A “good version” of the screen captured and stored. Then every time the application goes through the build process, the screen is re-captured and compared for differences to the master. Any deviations are noted and the build process fails.

Now this works for static screens. But the problem is that most of the time our applications do not have static screens, the content dynamically changes and therefore, everytime it does so, the build process would fail, invalidating the automated nature of the process. Not only that, but these screens render differently in each browser, so you end up taking 4-8 captures, which exponentially increases the potential to fail incorrectly. In essence these tests are too brittle and so not actually very useful, as they break too easily.

Taking a step back

Given that doing very low level atomic checking seems to be unhelpful, let’s analyse what the actual process is, that a human developer uses to validate a page by eye.

When I look at a page against a design, I don’t compare pixel by pixel. I compare a higher level. First I look at the design. From the design I create a number of mental rules. In my head I create a list of all the different font variations, the different colors used and the rough layout. If the design has too many variations in these things, then it is inconsistent and hence bad user design, in which case I end up going back to the designers and asking for a higher level of standardisation. When we have this basic checklist of “design principles”, we can compare the font size, weight and face, compare colors, compare widths, heights and alignments to the implementation. This enables us to take a design and an implementation and quickly gauge at a high level whether it is likely to be correct.

Taking this principle changed the way I started thinking about unit testing CSS, what if we could formalise this set of design principles and turn them into a programmatic set of rules that we could test each page against?

For this, my experiment led me to create cssUnit, a framework for checking style consistency.

Where cssUnit might help.

Like all software projects, not all processes are suitable for every situation, this is no exception. You will have to evaluate whether css unit testing is right for your project, the key factors I would take into account for this are, project lifespan, number of developers and size of site.

The scenarios in which cssUnit testing will be helpful are:

  • Large corporate web presence where there is a overall style guide but many different sites/microsites maintained by lots of developers
  • where you have a very fluid team - may often be short term freelancers
  • where you are training up a young/unfamiliar team of front-end developers,
  • situations where there is overlap between front end and backend - but not necessarily the possibility to maintain quality
  • co-located or remote teams

As well as being a tool to maintain quality - unit testing is also a way of communicating and distributing knowledge in a direct fashion, few developers will bother to spend the time reading the style guide, but many will learn the rules through failing tests.

What cssUnit is not.

cssUnit is not a number of things - I thought I would just mention the ones I did not mean it to be

Not cross-browser tested - although in principle it should be easy to make cross browser - it is not - not yet anyway - if it proves to be useful, then perhaps there is a case for making it cross-browser

Not beta - cssUnit is not by any means complete, and is as expressed before is more of an experiment, I have only coded for the scenarios I thought of, I’m sure there are better ways of doing this, but this is at least a starting point to explore how it might be done.

Not a service - lots of testing platforms have become services recently, but this is not currently my aim. There are many directions this could take, at the moment I’m not sure making it a service is the correct path.

Not easy - like all unit testing, cssUnit takes time to set up and implement in the beginning. The hope is that in the long term it saves you more time than it costs. It is also dependant on you having a strict style guide - with out standardisation in your design, cssUnit becomes useless.

animating alpha in PNG’s in IE7 cause black artifacts

Tuesday, September 29th, 2009

Just a quick entry to point out something that I found out recently. I’ve long had the problem in IE7 where applying opacity to an element with a PNG image as a background or image using jQuery (or any other library) results in the transparent pixels turning black. It seems the ever robust IE7 engine has a bug (oh my god who would have guessed?), but with an accident and a bit of research I have come up with a work around.

Back in the days before JavaScript libraries existed a developer often had to write their own cross browser transparency functions, somewhat of a rite of passage I would imagine, at least it was for me.

Having written a few of these routines myself, I was pretty confident I knew how jQuery was achieving this effect cross browser. In standardised browsers (FF, Safari, Opera, Chrome etc.) one has just to use the opacity property (- it wasn’t always this way, back in the pre FF2 days one had to use the -moz-opacity property as well) but in IE you have to use one of the wondrous non-standard propriety filters, a prospect that is about as attractive as participating in a Jade Goody munging contest.

The IE filters are notoriously SHIT and behave in a sinuos fashion to anything you might try and do with them. But as mentioned previously, the combination of the opacity filter and a transparent PNG (8 or 32) has the marvellous side effect of turning any transparent pixels in to black, until the filter is reset. Like so:

iescreen1

So, I spent some time trawling the web for workable answers or solutions but none seemed to present themselves. But then it struck me that on the same site I was working on I’d already acheived the effect and it hadn’t broken on IE7. How was this possible? I set about creating some test pages to figure out exactly what was needed for it to work in IE7. I discovered three vital steps that need to be taken.

  • Put the image or background image in a child of the element you are fading and fade the parent.
  • Position the element, it has to be relative or absolute, static doesn’t seem to work.
  • Put a background colour on the parent - this one really sucks but it seems the engine can’t hack it unless you do.

Then finally you will achieve a result like the following:

pngalphaexample_fixed

So that’s it, embrace the hacks and join me in the Microsoft hell of unmaintainable, bloated, bastardised semi opaque code. This development lark, It’s fun. Honest.

CSS Pre loaded - avoid FOUC with practical progressive enhancement using JS & CSS inheritance

Sunday, July 26th, 2009

Graceful degradation is an art form. The combination of XHTML, CSS and Javascript have never been one of coding beauty and will never win you any semantic accolades or the adoration of your clients or peers. Yet it is vital. In this day and age, progressive enhancement is a balance point between accessibility, usability and code optimization, on a large site you cannot afford to overlook it. So the question arises, what limited best practice can we draw up to make our lives easier and our products better? This article aims to offer a practical look at a set of technique’s used to help separate CSS and JS, to make apps more easily degradable, and to rid yourself of the dreaded FOUC (Flash of unstyled content).

I am a firm believer in separating out as much styling information as possible from JS to CSS. From a very basic level of having all static file references, colors & dimensions in CSS class selectors and NOT in the Javascript, to more advanced techniques of using CSS classes to control your animations (a feature native to Mootools and built in to jQuery using one of the many plugins). Anything to do with CSS in the JS needs to have a damn good reason to be there, otherwise rip it up, stop it from cluttering your logic code and put it in the CSS.

So to illustrate lets create a basic example of progressive enhancement with a standard tooltip on an element, where the behavior involves a div appearing on rollover.

<div id="links">
	<a href="#" class="tooltip_information">Link</a>
	<span class="tooltip">Something witty about this link</span>
</div>

Now, the basic initial approach may run along the lines of waiting for the DOM to load using a DOM load event, rooting through the DOM and finding all instances .tooltip and applying some CSS styles to them to position them and use the rollover behavior. As follows (all JS written in jQuery syntax) :

$(document).ready(function() {
	$("#links").css({position: "relative"});
	$(".tooltip").css({
		position: "absolute",
		top: "5px",
		left: "5px",
		display: "none"
	}).bind("mouseover", function() {
		$(this).css({
			display: "block"
		});
	});

});

Fine. It’s degradable, it works, but it’s messy and a bitch for anyone else to maintain and bug fix. Lets go through and see what we can clean up. First lets move our styling into the CSS.

.tooltip_Container {
	position: relative;
}

.tooltip_information {
	position: absolute;
	top: 5px;
	left: 0px;
	display: none;
}

.tooltip_information_visible {
	display: block;
}

This makes our JavaScript look like this:

$(document).ready(function() {
	$("#links").addClass("tooltip_Container");
	$(".tooltip").addClass("tooltip_information").bind("mouseover", function() {
		$(this).addClass("tooltip_information_visible")
	});

});

Sweet. Now I know this is a fairly simple example. You may want to have all kinds of fancy ‘fade’ or ‘movement’ effects going on. However this does show you, on a basic level, how much cleaner your JavaScript becomes if you move your style rules out into the CSS. Also, it means if you want to add more style changes, it’s a much easier process with a considerably smaller risk of breaking your JS logic due to missing a comma or semi colon. Consequently maintenance could even be taken over by folks who are less JS savvy, leaving you more time to build the next JavaScript implementation of coverflow or whatever it is UI coders do with their spare time…

Now, here’s where I change the paradigm and flip things on their head somewhat. The previous approach is fine for smaller web sites with limited interactivity, but once you add some other stuff going on and a heavy longer page, you start to run into speed and load time problems doing all these element lookups and events. So what can we do to mitigate these? Well, firstly, rather than using JS to add all these class names let’s leverage the power of CSS inheritance to help us out. Instead of adding a class to elements let’s add a generic one to the body, my favorite name is “JSEnabled”.

$(document).ready(function() {
	$(document.body).addClass("JSEnabled");
	$(".tooltip").bind("mouseover", function() {
		$(this).addClass("tooltip_information_visible")
	});

});

our CSS becomes :

.JSEnabled .links {
	position: relative;
}

.JSEnabled .tooltip {
	position: absolute;
	top: 5px;
	left: 0px;
	display: none;
}

.JSEnabled .tooltip_information_visible {
	display: block;
}

This allows you to deal with multiple JS CSS changes in a much simpler clean cut way and do it quickly in one hit using CSS inheritance, rather than multiple hits using JS to find all your elements. This does wonders for your IE6 load times and allows you to easily test what your site will look like without JavaScript enabled. It also further enhances the ability of others to easily extend the JS/CSS you have written without hacking around inside your precious code.

The final trick or fairy dust mentioned in the introduction is something that has long hampered progressively enhanced online apps. You are trying to build a progressively enhanced site but you’ve got a bit of an overweight lardy DOM, or more likely a poor web connection.
When this happens the DOM ready function just doesn’t cut it and often leads to a nasty FOUC side effect where the non JS page is rendered but the DOM ready doesn’t kick in early enough. Leaving the user with an ugly little animated scene of the page reordering itself to hide all the fun interactive bits - somewhat like the curtain coming up too early on the stage and the audience seeing all the props being put into place.

So how can we detect whether the page has JS capability before the content loads? We can’t just hard code the JSEnabled class onto the body, as this would break the progressive enhancement for anybody with JavaScript turned off. For a short and concise solution - see the following snippet to be embedded in the head of your HTML, before anything else:

var elements = document.getElementsByTagName("html");
elements[0].className += " JSEnabled"

Effectively this add the JSEnabled class to the html tag instead of the body, right at the beginning of the page load, allowing you to take advantage of your JSEnabled CSS right from the word ‘go’. It integrates particularly well with the new frameworks coming out at the moment that allow you to passivly download modules of your JS code post load for secondary functionality to speed up initial load time. But most importantly when the page does first load everything appears where it’s supposed to!

vote it on WebDevVote.com

Game changing CSS Image news

Thursday, June 25th, 2009

I spotted this on Ajaxian today:

Vlad Vuki?evi?, a leader in the Mozilla community (and brought us cool stuff like Canvas 3D!) has spoken up on the internals of the browser, which shows you the trade-offs for the spriting approach:

The biggest problem with CSS sprites is memory usage. Unless the sprite image is carefully constructed, you end up with incredible amounts of wasted space. My favourite example is from WHIT TV’s web site, where this image is used as a sprite. Note that this is a 1299×15,000 PNG. It compresses quite well — the actual download size is around 26K — but browsers don’t render compressed image data. When this image is downloaded and decompressed, it will use almost 75MB in memory (1299 * 15000 * 4). If the image didn’t have any alpha transparency, this could be maybe optimized to 1299 * 15000 * 3, though often at the expense of rendering speed. Even then, we’d be talking about 55MB. The vast majority of this image is blank; there is nothing there, no useful content whatsoever. Just loading the main WHIT page will cause your browser’s memory usage to go up by at least 75+MB, just due to that one image.

That’s not the right tradeoff to make for a website.

I know it’s fairly obvious but I never realised that the browser put all that uncompressed image data into memory before, but it explains A LOT.

For the last few years it seems we’ve focused on how to compress and compress the data we sent over the wire so our load times would be faster, but with this luxury of smaller file sizes we’ve fallen into a trap where we forgot how the browser would cope with all this extra data.

It’s a bit like when you order a 10 foot flat pack wardrobe from Ikea. The 100 mile delivery of the item from Ikea central to your house is easy. We have built a sophisticated road network and big articulated lorries and also you pay someone else to do all that bit for you.

The problem arises when it’s deposited on your doorstep, you wield the gigantic pieces of glass and chipboard through your house into your bedroom, unpack it, get out your drill, screw it all together.

Then you stop for a few hours wondering how the fuck you get this monstrously heavy behemoth off it’s back and against the correct wall of your room. This is the part we did not think about when we ordered it (hint: it usually involves several convoluted contortions, but don’t put pressure on the joints!).

I stole this image

I stole this image

When we made the initial decision, the only problem we could see was the large one immediately in front of us of how to get it to our house, we didn’t stop to think about the problems that might occur after that.  This is what we have done with images and browsers.

If it’s true it means a paradigm shift in everyday rounded corner box background images as well as an overall awareness for the weight of images in your site vs. client performance.

One of my favourite apps of this year is spotify, the reason is that as opposed to itunes’ avoirdupois nature spotify has a 16 meg ram footprint. This makes it much faster and responsive than 100meg+ depending on your library size (why itunes should be anywhere near this much and dependant on your library size is beyond me - it’s just one screen of pixels guys!). This matters to me and I suspect on a subconscious levels matters to most of spotify’s fans.  So the difference between my website devouring 150meg of your ram (if using firefox x5) vs 15meg DOES ACTUALLY MATTER.

It matters to you, your users and your clients as at the end of the day, your slowness is their bottom line.

Going back to the round corner box CSS case, it means in order to produce performant apps, we should NOT do this:

<div class="wrapper">

 <div class="inner">

 </div>

</div>

Where we stick long background image on two wrapper divs and then use the bottom one as the footer (example), but we actually HAVE to do this:

<div>

 <span class="header"></span>

 <div class="content"></div>

 <span class="footer"></span>

</div>

Where as opposed to the first example we have a repeating background on the content div which could potentially result in a 70meg ram saving for your app! This also aligns a lot better with OOCCS and I think is actually more readable on the flip side it is semantically worse as it has two extra empty divs, but lets face it two wrapping divs is hardly perfect and results in a massive image and slow site! An example is here.

a practical example of using custom events in jQuery

Sunday, June 21st, 2009

I’ve recently been converted to the practice of using jQuery custom events. At first I didn’t really see the point but then as time wore on it started to dawn on me how much more extensible it made the jQuery plug-in architecture and allowed a level of pseudo MVC, where the DOM translates literally into your view.

The example I’m going to illustrate it’s usefulness is a simple drag and drop, I recently found myself having to re-implement a drag and drop plug-in in jQuery as the standard UI plug-in although quick to implement was simply not very performant due to the incredible amount of configurability it has.

At first taking from the jQuery UI drag and drop template I started off with an implementation that was invoked by calling the following:

$("foo").dragLite({

containment : "parent",

axis : "xy",

startDrag: function() {foo.bar},

stopDrag: function() {foo.bar}

});

Pretty familiar stuff, like what you’d see on 99% of plug-ins.  So as the age old adage goes “If it ain’t broke…” until another developer came along a few months later and said “I want to hook into your stopDrag event”.

UH OH.

Well, you could do, but the only way to do that is to edit my original initialisation call and add in a call to your function in my anonymous function, which you could do, but is pretty messy, creates two fairly deep dependencies and could mean that if either of our code breaks, the functionality will not fail in a graceful way…

Clink. The penny drops. For the last few months, some people at work, some people on the web (dean edwards for one wrote an interesting post), and random tramps I met on the street, had been banging on and on about the custom event functionality in jQuery and this was why.

In my first example, I had had to pass my anon function into the last function through the initialise code, so my plug-in code looked something like this:

var dragStopped = function(event) {

//some stop drag code here

if(event.data.stopDrag) {

//execute the call back

event.data.stopDrag();

}

}

which as mentioned before means if anyone wants to add in an additional call back they have to do this:

$("foo").dragLite({

containment : "parent",

axis : "xy",

startDrag: function() {foo.bar();},

stopDrag: function() {foo.bar(); someOtherClass.someOtherCallBack();}

});

However, what if we abandon callbacks for custom events instead, so the plug-in code becomes:

var dragStopped = function(event) {

//some stop drag code here

//trigger custom event bindings

$(this).trigger("dragLite.stopDrag");

}

which won’t fail if we have no functions bound and our initialisation call becomes this

$("foo").dragLite({

containment : "parent",

axis : "xy"

}).bind("dragLite.stopDrag",foo.bar) ;

then all my other developer has to do in his code is

$("foo").bind("dragLite.stopDrag", someOtherClass.someOtherCallBack) ;

which he can do anywhere in the code, independent of whether the drag functionality has been implemented yet.

Pretty Neat, and most definitely worth doing for increased stability, better code flow and less work for you!