Accessibility Examples: ARIA Tooltip

A tooltip is a popup widget to display information related to an element in a page. The tooltip widget is displayed when the associated element receives focus or is hovered over with a mouse. The tooltip is again hidden if the element loses focus, the user moves the mouse cursor off of the element, or the user presses the escape key. Tooltips are not focusable.

Required ARIA attributes

The following attributes are needed to implement tooltips:

Markup

As an example of tooltip markup, below is a code snippet for a tooltip associated with a button:

<div class="tp-wrapper">
    <button class="tp-trigger" aria-describedby="tp-container">Example</button>
    <div id="tp-container" role="tooltip">This text describes the button.</div>
</div>

Placing the tooltip immediately after the triggering element in the page allows for the tip to be displayed on mouse hover via the CSS3 adjacent element operator (+). Note that it may be necessary to wrap the triggering element and the tooltip for the purpose of positioning the tooltip via CSS. The CSS for this example could be implemented as follows:

.tp-wrapper {
    position: relative; /* Allow tooltips to be easily positioned relative to the triggering element */
}
[role=tooltip] { /* hide tooltips by default */
    display: none;
    position: absolute;
    top: -2em;
    left: 1em;
    padding: 0.5em 1em;
    background-color: #666;
    border-radius: 5px;
}
[role=tooltip]:after { /* Add a downward arrow to style the tooltip */
    position: absolute;
    left: 20px;
    bottom: 10px;
    content: '';
    width: 0;
    height: 0;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
    border-top: 15px solid #666;
    border-bottom: none;
}
.tp-trigger:hover + [role=tooltip],
.tp-trigger:focus + [role=tooltip] {
   display: block;
}

JavaScript is necessary to hide the tooltip if the user presses the escape key. If the tooltip is displayed when the triggering element receives focus, then it should be dismissed when the element loses focus. If the tooltip is displayed due to mouse hover, then it should be dismissed when the mouse pointer is moved away from the triggering element.

Note: Once the tooltip has been dismissed with the escape key, the css to display the widget on hover and focus will not function. As such, JavaScript is needed to bind focus, mouseEnter, and mouseOut event handlers. The hover and focus CSS pseudoclasses can either be omitted or kept as a backup incase there is a problem with the page that prevents the JavaScript from executing. The example will function purely with CSS, minus the escape key functionality. Set a flag on focus and mouse events to prevent the tooltip from being dismissed via hover if it was triggered via mouse and vice versa.

Tooltip Widget Example