I am trying to make a div .description
that appears where the mouse is as it hovers over an element.
So far, I have this code for making the div appear in a fixed location:
JavaScript
x
17
17
1
$('.tooltip').mouseover(function(e) {
2
// var to link tooltips and hand to description
3
var target = $(this).attr('data-show');
4
5
// hide current description if showing
6
if ($('.description').is(':visible')) {
7
$('.description').fadeOut(0);
8
};
9
10
e.stopPropagation();
11
$('#' + target).fadeIn(400);
12
});
13
14
$('body').mouseover(function(){
15
$('.description').fadeOut(0);
16
});
17
It works fine, but instead of just have .description
appear, I need it to appear where the mouse hovers.
I tried adding this function:
JavaScript
1
5
1
function divPosition (event){
2
// pass mouse position to description div css
3
$(".description").css({top: event.clientY, left: event.clientX- 200});
4
};
5
but it didn’t work. I also tried adding the line within the function but i’m not sure how to pass the event argument.
Please see my JSfiddle: https://jsfiddle.net/bns4zp1q/2/
Advertisement
Answer
You can listen to the mousemove
event, and use your divPosition
function.
https://jsfiddle.net/agbuLop1/
JavaScript
1
7
1
$('.tooltip').mousemove(divPosition);
2
3
function divPosition (event){
4
// pass mouse position to description div css
5
$(".description").css({top: event.clientY, left: event.clientX- 200});
6
};
7