Kilian Valkhof

Front-end & user experience developer, Jedi.

Using CSS instead of javascript

CSS & HTML, 11 January 2007, 2 minute read

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

Tooltips!

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>
</a>

The CSS:


a span {
	display:none;
}
a:hover span {
	display:block;
	position:absolute;
	top:0;
	left:0;
	z-index:10;
}

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.

Discuss

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?

Thanks for Reading!

I am Kilian Valkhof, a front-end and user experience developer from the Netherlands.
Contact me or ping me on twitter.

  1. I see what you mean!

    There are so many things you can do with CSS which can be achieved with JS as well.

    I hope CSS doesn’t get too much functionality though, I like using JS where it’s needed but for basic effects like the one you’re on about using CSS would be a better idea!

  2. You’ve got a small typo in your post, you wrote <span<

  3. Thanks, fixed :)

Be the first to know about new releases!

Newsletter subscribers will be the first to know about new apps I release or new articles I write, here or elsewhere.

Low-volume. I will only email you when I have something exciting to share.