I am learning how to create tooltips based on a w3schools tutorial.
One problem I am faced with is the visibility of the tooltips when the hovered-upon text is close to a browser edge and the tooltip is displayed outside of the visible area.
Is there a standard way to prevent this (any approch (CSS, JS, ...) would be welcome)?
The idea I have right now is to calculate the coordinates of the tooltip depending on the size of the screen and the position of the tooltip anchor - but I would like to avoid reinventing the wheel.
A tooltip which expands to the top or to the bottom would be enough - maybe there is a "is completely visible" check which can be done to make a decision on the direction? This would be similar to what is in place in tooltips in SO:
You need to calculate if the position of the tooltip will be outside the window. In the example below I just add class .bottom
to the .tooltiptext
in this case.
The calculation is:
$('.tooltip').offset().top - $('.tooltiptext').height() < 0
In this case we should add that class.
The full example:
$('.tooltip').on('mouseenter', function() {
var $this = $(this);
var tooltip = $(this).find('.tooltiptext');
var offset = $this.offset();
tooltip.toggleClass('bottom', offset.top - tooltip.height() < 0);
// - just for case you want to change the default behavior - tooltip.toggleClass('top', $(window).height() + tooltip.height() < 0);
});
.footer {
position: absolute;
bottom: 0;
text-align: center;
padding-bottom: 10px;
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<style>
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 1s;
bottom: 125%;
}
.tooltip .tooltiptext.bottom {
bottom: auto;
top: 125%;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
</head>
<body style="text-align:center;">
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
<h2>Tooltip</h2>
<p>Move the mouse over the text below:</p>
<div class="footer">
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
</div>
</body>
</html>
http://output.jsbin.com/nemebob
I let you to change the arrow direction to top.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With