Marco Angelo Marco Angelo - 3 months ago 8
CSS Question

make div appear on mouse over

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:

$('.tooltip').mouseover(function(e) {
// var to link tooltips and hand to description
var target = $(this).attr('data-show');

// hide current description if showing
if ($('.description').is(':visible')) {
$('.description').fadeOut(0);
};

e.stopPropagation();
$('#' + target).fadeIn(400);
});

$('body').mouseover(function(){
$('.description').fadeOut(0);
});


It works fine, but instead of just have
.description
appear, I need it to appear where the mouse hovers.

I tried adding this function:

function divPosition (event){
// pass mouse position to description div css
$(".description").css({top: event.clientY, left: event.clientX- 200});
};


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/

Any help or insight into how I can improve my code would be really appreciated. thanks

Answer

You can listen to the mousemove event, and use your divPosition function.

https://jsfiddle.net/agbuLop1/

// =================tooltip animation
// detect user device
var screen = window.innerWidth;


$('.tooltip').mouseover(showDescription);
$('.tooltip').mousemove(divPosition);

function showDescription(e) {
  // var to link tooltips and hand to description
  var target = $(this).attr('data-show');

  // hide current description if showing
  if ($('.description').is(':visible')) {
    $('.description').fadeOut(0);
  };
  e.stopPropagation();
  $('#' + target).fadeIn(400);
}

$('body').mouseover(function(event) {
  $('.description').fadeOut(0);
});
function divPosition (event){
  // pass mouse position to description div css
  $(".description").css({top: event.clientY, left: event.clientX- 200});
};

// ==========image loader

$('.eye').click(function(e) {
     // var to link tooltips and hand to description
    var target = $(this).attr('data-show');
    // hide current image
    $('.image').fadeOut(0);
    // load new image

    e.stopPropagation();
    $('#' + target).fadeIn(400);
}) /
// ===========back button
$('.back').click(function(e) {
    $('.image').fadeOut(0);
    $('#machine1').fadeIn(400);
})