A lesson learned
Today I thought it would be cool and useful to have the time
element display the value of its datetime
attribute on hover, as sometimes the text that is displayed isn’t fine enough. So I quickly built something that did this in JavaScript only to find out a much easier method later on.
Earlier today I was making some changes to this website, including text changes. On my about page I have a time
element whose content is text and no-one might know that it is actually a time
element:
<time datetime="2012-07-31">Recently</time>
Therefore I thought it might be useful to build a quick JavaScript that would display the contents of the element’s datetime
attribute when a user hovered over the time
element.
And thus Time Hover was born and added to GitHub.
Then Alex Gibson (the fiend) tweeted:
Nice. I wonder could you do something close using just CSS? e.g. time:hover:after { content: attr(date time); }. Just an idea…
So I quickly tried it out and indeed he is correct, it works just as fine and requires no JavaScript overheads or inserting of items into the DOM so is arguably much better.
time:hover:after {
content:attr(datetime);
font-family:arial;
position:absolute;
opacity:.8;
font-size:.5em;
text-align:center;
margin-top:-.5em;
line-height:1.2em;
background:#ccc;
}
However, the datetime
string can be almost unreadable, e.g. 2006-09-24T05:00-07:00 and this being displayed on hover might not help much. So in this case the JavaScript solution is probably better as it would allow you to format the value of datetime
so it contains a more readable format.
A lesson learned
Regardless, it just goes to show that there are often simpler solutions available out there, and no matter how many years you’ve had in the industry, you don’t always see them. Sometimes you just need to sit back and think about something a bit more before diving straight in.