When writing JavaScript, very frequently I need to check if a given thing exists in a list of things. Every single time I need to look up the function that does that for the sort of list I’m working with. You see, there are three possible options: includes(), contains() and has() and I mix them […]
Using CSS instead of javascript
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:
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?