Reputation: 11524
I have some toy code for a tooltip. It works okay, except that when you mouse into the tooltip it gets hidden with this logic.
I'm banging my head trying to figure out a clean way to get the tooltip to stay visible when you mouse into it, and disappear when you mouse out of both areas. Anyone have a suggestion?
HTML
<div id="container">
<div id="div1"></div>
<div id="div2"></div>
</div>
Javascript
var div1 = $("#div1");
var div2 = $("#div2").hide();
var hoverTimer;
div1.mouseenter(function(e) {
var x = e.pageX;
var y = e.pageY;
div1.mousemove(function(e) {
x = e.pageX;
y = e.pageY;
});
hoverTimer = window.setTimeout(function() {
div2.css("left", x);
div2.css("top", y);
div2.show();
}, 400);
});
div1.mouseleave(function(e) {
window.clearTimeout(hoverTimer);
div2.hide();
});
CSS
#container {
position: relative;
}
#div1 {
float: left;
clear: none;
width: 200px;
height: 200px;
background-color: green;
}
#div2 {
position: absolute;
width: 100px;
height: 100px;
background-color: blue;
}
Upvotes: 0
Views: 634
Reputation: 1305
Best way for showing tooltip is using css only.
e.g
suppose I have element to which i have to give tooltip . i will give data attribute to that element and then with css i will access that attribute and then will show tooltip like below
<a data-tool-tip="my tool tip"> my link goes here</a> this is other text
and css will be like below
a[data-tool-tip]{
position:relative;
}
a[data-tool-tip]::after {
content: attr(data-tool-tip);
display:block;
position:absolute;
background:gray;
padding:10px;
color:white
border-radius:5px
font-size:0.8em;
bottom:100%;
left:0;
white-space:nowrap;
transform:scale(0);
transition:transform ease-out 150ms;
}
a[data-tool-tip]:hover::after {
transform:scale(1);
}
As tool-tip prepended to element itself using ::before
selector it will be visible after mouse enter also;
output will be like below
Upvotes: 0
Reputation: 324720
You create the mousemove
event, but aside from setting two variables you never actually move the tooltip. Try this instead. Note I added a 16-pixel "margin" on the mouse position - this is to make it more inline with actual tooltips, and prevents the flickering effect.
Upvotes: 4