I'm creating a CSS based tooltip that is going to have a lot of content in the tooltip and instead of being in a static place I was wondering is there a easy way to make it follow the cursor as you hover over the link.
Here is a example of the CSS based tooltip
<div class="couponcode">First Link
<span class="coupontooltip">Content 1</span>
</div>
.couponcode:hover .coupontooltip {
display: block;
}
.coupontooltip {
display: none;
background: #C8C8C8;
margin-left: 28px;
padding: 10px;
position: absolute;
z-index: 1000;
width:200px;
height:100px;
}
http://jsfiddle.net/q46Xz/
Something like this
var tooltip = document.querySelectorAll('.coupontooltip');
document.addEventListener('mousemove', fn, false);
function fn(e) {
for (var i=tooltip.length; i--;) {
tooltip[i].style.left = e.pageX + 'px';
tooltip[i].style.top = e.pageY + 'px';
}
}
FIDDLE
Here's a version that keeps into account the height and width of your window:
function showTooltip(e) {
var tooltip = e.target.classList.contains("coupontooltip")
? e.target
: e.target.querySelector(":scope .coupontooltip");
tooltip.style.left =
(e.pageX + tooltip.clientWidth + 10 < document.body.clientWidth)
? (e.pageX + 10 + "px")
: (document.body.clientWidth + 5 - tooltip.clientWidth + "px");
tooltip.style.top =
(e.pageY + tooltip.clientHeight + 10 < document.body.clientHeight)
? (e.pageY + 10 + "px")
: (document.body.clientHeight + 5 - tooltip.clientHeight + "px");
}
var tooltips = document.querySelectorAll('.couponcode');
for(var i = 0; i < tooltips.length; i++) {
tooltips[i].addEventListener('mousemove', showTooltip);
}
.couponcode {
color: red;
cursor: pointer;
}
.couponcode:hover .coupontooltip {
display: block;
}
.coupontooltip {
position: absolute;
white-space: nowrap;
display: none;
background: #ffffcc;
border: 1px solid black;
color: black;
padding: 5px;
z-index: 1000;
}
Lorem ipsum dolor sit amet, <span class="couponcode">consectetur
adipiscing<span class="coupontooltip">This is a tooltip</span></span>
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in <span
class="couponcode">reprehenderit<span class="coupontooltip">This is
another tooltip</span></span> in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est <span
class="couponcode">laborum<span class="coupontooltip">This is yet
another tooltip</span></span>.
(see also this Fiddle)
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