
A simple code snippet that allows tool-tips to be displayed on HTML controls when the mouse hovers over them or when the control is clicked (e.g. touched on a mobile device). Useful in scenarios where you want a simple, modern, tool-tip without the weight of a 3rd party library.
The solution consists of 3 parts:
- CSS Classes.
- A JavaScript function.
- Appropriately formatted HTML elements.
Here are the CSS Classes:
.hover-or-click-title-container {
position: relative;
}
.hover-or-click-title {
display: none;
z-index: 1000;
position: absolute;
background-color: #fffccc;
border: 1px solid #90801a;
border-radius: 3px;
padding: 4px;
min-width: 400px;
}
.hover-or-click-title.show {
display: block;
}
Code language: CSS (css)
Here’s the JavaScript (currently using jQuery):
function toggleTitleOnHoverOrClick(show) {
var target = $(window.event.currentTarget ? window.event.currentTarget : window.event.target);
var title = target.parent().find('.hover-or-click-title');
if (title.length > 0) {
var showTitle = null;
if (typeof show === 'boolean') showTitle = show;
else showTitle = !title.hasClass('show');
if (showTitle) {
var top = (target.position().top + ((target.height() / 3) * 2));
var left = (target.position().left + (target.width() / 2));
var leftOnPage = title.parent().offset().left + title.offset().left;
if (leftOnPage + title.width() > window.innerWidth &&
leftOnPage - title.outerWidth() < window.innerWidth
) {
left -= title.outerWidth();
}
title.css('top', top + 'px');
title.css('left', left + 'px');
title.addClass('show');
} else {
title.removeClass('show');
}
}
}
Code language: JavaScript (javascript)
Here is an example of how to implement a HTML control fragment which supports tool-top hover over / on-click:
<div class="hover-or-click-title-container">
<div onclick="toggleTitleOnHoverOrClick()" onmouseenter="toggleTitleOnHoverOrClick(true)" onmouseout="toggleTitleOnHoverOrClick(false)">
This is the item that can be hovered over or clicked to show the tool-top / title.
</div>
<div class="hover-or-click-title">This is the hover-over/click-to-show title text</div>
</div>
Code language: HTML, XML (xml)