My Location

Apr 15, 2009

Firing script with an anchor

Quite often I want an anchor (link) to execute a script, and usually I fall into the trap of trying to use onclick and set href to an empty string or leave it out entirely. However, href is a required attribute and empty string is a valid value which means "link to self", so the correct solution is to put the script into the href attribute, prefixed by "javascript:".

For example, here is an anchor which does the same thing as pressing the browser's Back button:

<a href="javascript:history.back();">Back</a>

Thanks JWhittaker for setting me straight.

Apr 9, 2009

Always show a vertical scroll bar

IE always shows a vertical scroll bar for a web page, regardless of whether or not the page is long enough to require one. This is nice for sites with a fixed-width centred layout and a combination of short and long pages, because it means the horizontal position stays exactly the same on every page. Other browsers (Firefox and Chrome at least) don't do this by default.

Finally I've looked up how do this in these other browsers, and discovered that it's actually quite easy. It's not even a hack! Just a CSS rule ...

html {overflow-y: scroll;}

Apr 8, 2009

Styling table columns

It seems so natural to want to set colour and alignment on columns of a table. But CSS2.1 does not allow it, it only allows you to set width, visibility, border and background. Hixie explains why. Internet Explorer supports it, but no-one else does.

The workaround is to use CSS selectors as follows:

#table55 td:first-child { text-align:left; } /* col 1 */
#table55 td:first-child+td { text-align:center; } /* col 2 */
#table55 td:first-child+td+td { text-align:right; } /* col 3 */

This works in CSS-compliant browsers including IE7 and above. Thanks to Simon Pieters for this one.