en.javascript.info/2-ui/2-events/03-event-delegation/4-behavior-tooltip/solution.view/index.html
Ilya Kantor ab9ab64bd5 up
2017-03-21 14:41:49 +03:00

80 lines
2 KiB
HTML

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
height: 2000px;
/* make body scrollable, the tooltip should work after the scroll */
}
.tooltip {
position: fixed;
padding: 10px 20px;
border: 1px solid #b3c9ce;
border-radius: 4px;
text-align: center;
font: italic 14px/1.3 arial, sans-serif;
color: #333;
background: #fff;
box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);
}
</style>
</head>
<body>
<p>LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa</p>
<p>LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa</p>
<button data-tooltip="the tooltip is longer than the element">Short button</button>
<button data-tooltip="HTML<br>tooltip">One more button</button>
<p>Scroll the page to make buttons appear on the top, check if the tooltips show up correctly.</p>
<script>
let tooltipElem;
document.onmouseover = function(event) {
let target = event.target;
// if we have tooltip HTML...
let tooltipHtml = target.dataset.tooltip;
if (!tooltipHtml) return;
// ...create the tooltip element
tooltipElem = document.createElement('div');
tooltipElem.className = 'tooltip';
tooltipElem.innerHTML = tooltipHtml;
document.body.append(tooltipElem);
// position it above the annotated element (top-center)
let coords = target.getBoundingClientRect();
let left = coords.left + (target.offsetWidth - tooltipElem.offsetWidth) / 2;
if (left < 0) left = 0; // don't cross the left window edge
let top = coords.top - tooltipElem.offsetHeight - 5;
if (top < 0) { // if crossing the top window edge, show below instead
top = coords.top + target.offsetHeight + 5;
}
tooltipElem.style.left = left + 'px';
tooltipElem.style.top = top + 'px';
};
document.onmouseout = function(e) {
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
};
</script>
</body>
</html>