Kilian Valkhof

Building tools that make developers awesome.

Using CSS instead of javascript

CSS & HTML, 11 January 2007, 2 minute read

Recently, while I was working on a new website, I caught myself doing something stupid: Adding javascript just because it was javascript. Sound’s confusing? Allow me to explain:


You see, I wanted a tooltip on hover. Because I was already using the excellent Jquery library, I immediately started looking for a plugin that did tooltips. This was found quite fast: Interface Tooltip.

Initially it worked well, except for some bug that made the tooltip blink and disappear if you moved from one <a> to another within the delay time. In my design I had <a>‘s with display:block; lined up, so this was happening all the time.

Uhm. Wait.

And then it struck me: Why the hell am I using a whole javascript function, when I can achieve the same with a little extra code and css? so I removed the javascript (Saving kB and a http request), added a <span> within the <a> with the text I wanted to appear, hid it using css, and positioned and styled it using the :hover pseudo-class. It might not have fancy fade-in effects, but it always works.

the code:

<a href="#">
	<img src="image.png" alt="link to #" />
	<span>The text for my tooltip</span>

The CSS:

a span {
a:hover span {

I omitted classes and other stylings to make the code more clear. Obviously the span will most likely have more markup

The lesson

So there is my lesson for today, do not get caught up in fancy effects when there is a better working alternative. I always strive to use as less code as possible, so why wouldn’t I expand that to javascript, too.


What are your experiences with this. Do you often catch yourself adding more code or files then you actually need for your site to function? If so, why?

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!