Random Channel Random Channel - 6 months ago 30
jQuery Question

Detect when an image enters a div?

I am creating a maze game, and I want to detect when the image following the cursor reaches a certain div, the finishing point. I have the image following the mouse, and I have the container that the image will be in. When the image reaches the div, I want something to trigger, lets say an alert. How can I achieve this?





var startMove;

$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});

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



html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
div{
margin-left: 500px;
width: 200px;
height: 50px;
background-color: green;
}

<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"/>
<div></div>





Jsfiddle: https://jsfiddle.net/3x7cgLdr/25/

Answer

You already have a flag called startMove that is active whenever the cursor is dragged, use the mouseenter event on the target div as follows:

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;
      $('html').removeClass('showCursor');
    }
    if(startMove){
        $("#image").css({left:e.pageX, top:e.pageY});
    }
    else{
        $('html').addClass('showCursor');
    }
});

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

$("#drop").mouseenter(function(){
 if(startMove)
   alert("Success");
});

.

<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>

<div id="drop">
</div>

.

html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}

#drop{
  width:100px;
  height:100px;
  background:green;
  position: absolute;
  left:200px;
  top: 300px;
  z-index:99
}

see a demo: https://jsfiddle.net/hycd913y/