Follow the div with a jquery function with mousedown, mousemove, mouseup [duplicate]

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>
    var posX, posY;
    $(document).on('click', mueve);
    function mueve (e) {
        posX = e.pageX - 20;
        posY = e.pageY - 20;
        $('.item').animate({left: posX, top: posY})


    background: #bbb;
    height: 40px;
    width: 40px;
    position: absolute;
    border-radius: 50%;
    left: 0;
    top: 0;



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);

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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.