sticky tooltips
by Soviut
HTML
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
</div>
<div class="tooltip">
<button class="close">X</button>
<p>This is a tooltip</p>
</div>
CSS
body {
font-family: arial, helvetica, san-serif;
}
.container {
position: relative;
}
.item {
display: block;
position: absolute;
width: 60px;
height: 60px;
background: cornflowerblue;
cursor: pointer;
}
.item:nth-child(2) {
top: 60px;
left: 50%;
}
.tooltip {
display: none;
position: absolute;
width: 200px;
height: 150px;
z-index: 1000;
background: salmon;
}
.tooltip--sticky {
display: block;
}
.close {
display: none;
position: absolute;
right: 5px;
top: 5px;
border: solid 1px white;
color: white;
background: transparent;
cursor: pointer;
}
.close--sticky {
display: block;
}
JavaScript
$(function() {
var sticky = false;
var $tooltip = $('.tooltip');
var $close = $tooltip.find('.close');
function updateTooltip($item, hovering) {
$tooltip.toggleClass('tooltip--sticky', hovering || sticky);
$close.toggleClass('close--sticky', sticky);
$tooltip.css({
top: $item.offset().top + $item.outerHeight() + 'px',
left: $item.offset().left + 'px'
});
}
$('.container .item')
.on('mouseenter', function() {
if (!sticky) {
updateTooltip($(this), true);
}
})
.on('mouseleave', function() {
if (!sticky) {
updateTooltip($(this), false);
}
})
.on('click', function() {
sticky = true;
updateTooltip($(this));
});
$tooltip.find('button.close').on('click', function(e) {
e.preventDefault();
sticky = false;
updateTooltip($(this));
});
});