jQuery replacing mouse cursor

Issue

I’m trying to replace the mouse cursor with an image.

I have the following html:

<div id="content-bg">
   <img src="path"/>
</div>
<div id="mouse"></div>

CSS:

#content-bg{
    background:url(../img/frontend/content-bg.png) top left no-repeat;
    width: 968px;
    height: 552px;
    position:relative;
}

#mouse {
     cursor: none;
     width: 75px;
     height: 76px;
     background: url("../img/frontend/cross.png") no-repeat center;
     position: absolute;
    display:none;
     top: 0;
     left: 0;
     z-index: 10000;
}

javascript:

$(document).ready(function(){
     $('#content-bg').mouseout(function(){
          $('#mouse').hide();
          $(this).css("cursor","none");
          return false;
     });
     $('#content-bg').mouseenter(function(){
          $('#mouse').show();
          return false;
     });
     $('#content-bg').mousemove(function(e){
          var x = e.clientX - $(document).scrollLeft() - 37.5;
          var y = e.clientY + $(document).scrollTop() - 38;
          $('#mouse').css('left', x).css('top',y);
     });
});

The mouse image is on the right place but seems to be blinking and flashy. The transitions aren’t as smooth as I wanted. Somehow it seems that the mouseout and mouseenter events are triggered every time I move the mouse inside the content-bg div.

Any idea how I can solve this?

Solution

As has been pointed out in comments, your mouseout occurs when your mouse suddenly hovers #mouse, as it appears.

You need to cancel out these events manually:

 $('#content-bg').mouseout(function(e){
      if($(e.relatedTarget).is('#mouse')) { return false; }
      $('#mouse').hide();
      $(this).css("cursor","none");
      return false;
 });

 $('#content-bg').mouseenter(function(e){
      if($(e.fromElement).is('#mouse')) { return false; }
      $('#mouse').show();
      return false;
 });

Answered By – David Hedlund

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.