ahzep
ahzep

Reputation: 180

Div following pointer on hover

I want to show a floating div that follows the pointer when you're hovering certain divs, so far I found this piece of code with jquery that works when hovering the whole body, but what I want is to work on certain divs:

CSS

<div id="tail">mouse tail</div>

Jquery

$(document).bind('mousemove', function(e){
    $('#tail').css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
});

I tried bind to specific selector but it didn't work.

The div should disapear when you hover outside the div and reappear when you hover in.

Upvotes: 3

Views: 1058

Answers (2)

Andu Andrici
Andu Andrici

Reputation: 853

Target the specific divs, give them onmouseenter/onmouseleave events:

#tail {
  position: fixed;
}

.hidden {
  display: none;
};

window.addEventListener("mousemove", function(e){
  $('#tail').css({
   left:  e.pageX + 20,
   top:   e.pageY
  });
});

var myDiv = document.getElementById('tail');
var targets = Array.from(document.getElementsByClassName('myTargets'));

targets.map(function(target){
    target.addEventListener('mouseenter', function(){
        document.getElementById('tail').classList.remove('hidden')
    });
    target.addEventListener('mouseleave', function(){
        document.getElementById('tail').classList.add('hidden')
    });
});

Upvotes: 1

004123
004123

Reputation: 270

Just set the div display to none when the mouse leaves and display block when it enters

$('.something').bind('mousemove', function(e){
    $('#tail').css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
});

$('.something').bind('mouseleave', function(e){
    $('#tail').css({
       display:  'none'
    });
});
$('.something').bind('mouseenter', function(e){
    $('#tail').css({
       display:  'block'
    });
});
#tail {
  position: fixed;
  display: none;
}

.something {
  width: 200px;
  height: 160px;
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tail">mouse tail</div>

<div class='something'> stuff </div>

Upvotes: 5

Related Questions