How to create tooltips in tables for HTML
I recently started to collect the User Agents and Referrers for the statistics on my sites, as I found these information invaluable to perform analysis and targeted marketing. These values are helpfully automatically embedded into the Request object's environment as HTTP_USER_AGENT and HTTP_REFERER, so it is simply a matter of recording them into the database together with other fields when registering a hit. Yes I know you can use Google Analytics, but even this fantastic tool does not tell me how visitors found my site and what kind of device/browser they use to reach me on a per click basis. Having this information at my disposal is a real eye opener, and I can already think of a few things I can do to take advantage of this additional data.
I started including these new fields into the reporting pages, and discovered a minor problem, in that these values tend to be rather long that they take up much of the screen estate and causes each row to become rather fat vertically. Not very pleasing to the eyes at all. After a bit of tinkering, I got the results I desired, and here is how I did it.
Each entry shown will simply display the first 20 to 40 characters of the User Agent and Referrer, then if I want to see the rest of the string, I simply have to hover my mouse cursor over the truncated field. This is done very simply by using a new attribute in html called title, which should be supported by most modern browsers.
To support the automatic truncation of strings which are longer than, say 40, characters, you add a utility method into app/helpers/application_helper.rb
return str if str.nil?
return str if str.length <= len
Then, in my view for the reporting page, say app/views/report/hits.rhtml, I simply build the HTML for the User Agent column as
<td title='<%= hit.user_agent %>'><%= trim(hit.user_agent,40) %></td>
Which essentially dumps the whole User Agent string into the title attribute of the <td> element, then displays the first 40 characters of the same string in the HTML table. If you hover over the cell containing the truncated value, the browser takes over and displays the whole string as a popup tooltip, as shown in the screenshot above.
Of course, you should safeguard the value you embed into the title attribute of the <td> element against inclusion of the single quote, which will cause the attribute to be truncated prematurely.