Random Channel Random Channel - 6 months ago 24
Ajax Question

Is it possible to make an image move with the cursor when the cursor reaches the image?

I am creating a game, based off of an image moving with the cursor. I don't want the player to be able to cheat by moving the mouse outside of the box, and then moving the mouse to the finish. If using the setup I have currently, the image will move to where my mouse is. Any idea?

Code:





$(document).mousemove(function(e){
$("#image").css({left:e.pageX, top:e.pageY});
});

* {cursor: none;}
#image{
position:absolute;
width:25px;
height:auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>





JsFiddle: https://jsfiddle.net/3x7cgLdr/

Answer

I don't know if that is what you want, but I think it will help.

I defined var startMove which will be false when the cursor leave the document and will not be true until the mouse near by 50 to the image and then the image will start move. https://jsfiddle.net/IA7medd/3x7cgLdr/2/

var startMove;
$(document).mousemove(function(e){
    var difLeft = $('#image').offset().left - e.pageX;
    var difTop = $('#image').offset().top - e.pageY;
    if(difLeft < 50 && difLeft > -50 && difTop < 50 && difTop > -50 ){
      startMove = true;
    }
    if(startMove){
        $("#image").css({left:e.pageX, top:e.pageY});
    }
        checkCursor();
});

$(document).mouseleave(function(){
    startMove = false;
})

function checkCursor(){
    if(startMove){$('html').removeClass('showCursor');}
  else{$('html').addClass('showCursor');}
}

This added into the whole code:

  

 var startMove;
$(document).mousemove(function(e){
    var difLeft = $('#image').offset().left - e.pageX;
    var difTop = $('#image').offset().top - e.pageY;
    if(difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10 ){
      startMove = true;
    }
    if(startMove){
    	$("#image").css({left:e.pageX, top:e.pageY});
    }
		checkCursor();
});

$(document).mouseleave(function(){
    startMove = false;
})

function checkCursor(){
	if(startMove){$('html').removeClass('showCursor');}
  else{$('html').addClass('showCursor');}
}
    
    html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>      
    <img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>

Comments