↑
Main Page
Custom tooltips
Custom tooltips
Another interesting use of the
style
object is to create custom tooltips, which are those helpful yellow
boxes that appear when you move a mouse over an image button. By using the
title
attribute, HTML
elements can provide plain text tooltips, such as this:
<a href=”http://www.wrox.com” title=”Wrox Site”>Wrox</a>
However, these plain text tooltips may not be enough. Suppose you want to create a tooltip with bold or
italic text, or maybe even an image, you can do so by creating a hidden
<div/>
that is displayed only
when the mouse moves over its designated target. This is essentially the same as the rollover code, with
one extra step: moving the
<div/>
into a position close to the mouse. To correctly position the
<div/>
,
you can make use of the
clientX
and
clientY
properties of the
event
object. Note that because these
properties are available in all instances of the
event
object, you don’t need to use the
EventUtil
object
created earlier in the book:
<html>
<head>
<title>Style Example</title>
<script type=”text/javascript”>
function showTip(oEvent) {
var oDiv = document.getElementById(“divTip1”);
oDiv.style.visibility = “visible”;
oDiv.style.left = oEvent.clientX + 5;
oDiv.style.top = oEvent.clientY + 5;
}
function hideTip(oEvent) {
var oDiv = document.getElementById(“divTip1”);
oDiv.style.visibility = “hidden”;
}
</script>
</head>
<body>
<p>Move your mouse over the red square.</p>
<div id=”div1”
style=”background-color: red; height: 50px; width: 50px”
onmouseover=”showTip(event)” onmouseout=”hideTip(event)”></div>
<div id=”divTip1”
style=”background-color: yellow; position: absolute; visibility:
hidden; padding: 5px”>
<span style=”font-weight: bold”>Custom Tooltip</span><br />
More details can go here.
</div>
</body>
</html>
The DOM style methods are not supported by Internet Explorer. For this reason, it is
best to use properties of the
style
object to get and set CSS properties.
307
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 307
Free JavaScript Editor
Ajax Editor
©
→