Definition tooltips with jQuery
Published .
I recently came across a topic on a certain Swedish forum I frequent where the poster wondered whether you could create simple tooltips with definitions for certain words. The post immediately got my attention and I started working on a small implementation of this using jQuery and the excellent <dl> element in HTML.
The result was very good indeed. It uses jQuery and the jQuery tools (conveniently fetched from Google and flowplayers CDN, respectively) to wrap all occurrences of certain words in a <span> element with a predefined class. These elements are then hooked to their respective <dd> element, which displays as a tooltip when you hover the word. Add some nifty CSS to style the tooltip and @@s and suddenly you've got excellent definition tooltips.
@aragraphs of text, of course); first, we fetch jQuery and jQuery tooltips from their CDNs:
pre(brush:html).
Then, we need the actual JS doing the work (feel free to put this in an external JS file, just remember to load it after jQuery):
pre(brush:js). $(document).ready(function(){
$("#definitions dt").each(function(i, e){
var t = $(e).text();
$("p").each(function(j, p){
$(p).html($(p).html().replace(RegExp(t, 'g'), ''t''));
});
});
$("#definitions dt+dd").each(function(i, e){
$(e).attr('id', 'dfn-'+$(e).prev("dt").text().replace(" ", "-"));
});
$("span.def").each(function(i, e){
$(e).tooltip({
effect: 'toggle',
tip: '#dfn-'+$(e).text().replace(" ", "-")
});
});
$("#definitions").css('display', 'inline');
$("#definitions dt").css('display', 'none');
$("#definitions dt+dd").addClass('tooltip');
});
If you want the script to look in other elements, simply change $("p") on line 4 to another CSS selector. You could make it stricter, or include list elements, for example.
We need some styles as well. This (preferably in your external CSS document) should suffice, but you could change it:
pre(brush:css). .def{
color: #5B7E60;
border-bottom: 1px dotted;
cursor: pointer;
}
.tooltip{
width: 15em;
padding: 1em;
background: #eee;
border: 1px solid #ccc;
display: none;
}
Lastly, we put all definitions in one <dl>, with the id definitions. This is rather important:
pre(brush:html).
- fissile material
- A material that is capable of sustaining a chain reaction of nuclear fission, such as enriched uranium or plutonium.
- TNT
- Trinitrotoluene, a highly explosive compound
There you go! Space-efficient, bandwidth-efficient, easily maintainable, unobtrusive and wonderful.
No trackbacks
Writing about this post? A reply, retort, reaction? Use the trackback URI below to automatically create a link to your entry!
⟨http://blog.sigurdhsson.org/cgi-bin/mt/mt-tb.cgi/342⟩
One comment
Looks nice. BTW, if you use the jQuery Tools CDN, you don’t need to include jQuery separately—jQuery and the Tools are served together so you don’t need the Google CDN.
Join the discussion!