0

I wanna make a jquery function that "follow the div when it is on mousedown" - So the div on my page follows the cursor, as the mouse moves, when the mouse button is down.

and when the mouse button is up the div stay in the last position the mouse down was.

<script src="jquery-2.0.3.min.js"></script>
<script>
    var posX, posY;
    $(document).on('click', mueve);
    function mueve (e) {
        posX = e.pageX - 20;
        posY = e.pageY - 20;
        $('.item').animate({left: posX, top: posY})
    }
</script>

css:

.item{
    background: #bbb;
    height: 40px;
    width: 40px;
    position: absolute;
    border-radius: 50%;
    left: 0;
    top: 0;
}
Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59

1 Answers1

1

Boom, check this out: Fiddle.

Here's the javascript:

var posX, posY, clicked = false;
function mueve (e) {
    clicked = true;
    posX = e.pageX - 20;
    posY = e.pageY - 20;
    $('.item').animate({left: posX, top: posY});
}
$(document).on('mousedown', mueve);
$(document).on('mouseup', function(e) {
    clicked = false;
});
$(document).mousemove(function(e) {
    if (clicked) {
        $('.item').stop(true, true);
        mueve(e);
    }
});

What I did was: when you click down, you change the variable clicked to true, so when you move the mouse it will move the div with class 'item'. Also, you have to clear each queued animation before updating positions.

Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59
  • If the parent div contains another child div having the word `click me` such that it looks like the mouse is always over that text but the whole parent div moves with it, how to modify that? I tried with adding the `.item` in the child div but only the child moves not the parent div as a whole? – arjun Sep 14 '17 at 19:37