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?
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!
Related articles
CSS & HTML , 6 October 2020There are many different ways to achieve the same layout in CSS and HTML. Some are now frowned upon, like tables or floats, and others tend to overlap somewhat, but have a clear specific purpose, like Flexbox and Grid. But CSS has another layout engine, and it’s one that has been part of CSS since…
Javascript , 19 May 2020Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code. Creating downloadable files with JavaScript in your browser only takes a few lines of code. Check out the…
CSS & HTML , 3 July 2016 $ npm install postcss-dutch-stylesheets …