Monday, 30 September 2013

Showing tooltip for a DOM element using CSS.

Some websites show tooltips for input controls to help user enter the correct values. This not only provides for better user experience, but also potentially reduces the server network traffic as there are less chances of the failed validation at the server end, and the resultant transmission of error messages from the server to the user.

The question is how to show the tooltip to the user as a DOM element doesn't expose any property for tooltip? The answer lies in using CSS. Let's see an example of how it is done.

<!DOCTYPE html>
<title>CSS Tooltip</title>
div {position: relative;}
#nameTip {position: absolute; left: 20%; top: 8%;}
span {display: none;}
div:hover span{display: inline; color: green; background-color: yellow;}
<legend>Student Information</legend>
<label id="studentName">Student name:</label>
<input type="text" id="studentName">
<span id="nameTip">Minimum allowed length is 3, and max length is 12</span>
<label id="dob">Date of birth:</label>
<input type="text" id="dob">
<span id="dobTip">Date should be in the format like 2013-29-09</span>
<button type="submit">OK</button>

See the screenshot below of the tooltip popped up (the mouse is not visible in the screenshot, and I don't know how to capture it):

PS: I later discovered that DOM Elements expose a attribute called "title", and setting the value of this attribute effectively works as a tooltip for that element.

No comments:

Post a Comment