user4950475
user4950475

Reputation:

Move a div horizontally with mouse using jQuery

I am trying to move a div horizontally on mouse moving. Here's my code so far:

HTML:

<div id="test"></div>

CSS:

#test {
   width: 300px;
   height: 60px;
   background-color: #333;
   position: absolute;
   top: 0;
   left: 20px;
}

JS:

$(document).ready(function(){

$('#test').bind('mousedown', function (e) {
    $(document).bind('mousemove', function (e) {
        var diff = e.pageX - $('#test').offset().left;
        $('#test').css('left', diff + 'px');
    });
});

$(window).bind('mouseup', function (e) {
    $(document).unbind('mousemove');
});

});

Div actually moves, but in a strange way. https://jsfiddle.net/ktLskwos/1/ How can I make it work correctly?

Upvotes: 0

Views: 2353

Answers (2)

A. Abramov
A. Abramov

Reputation: 1865

Why do you add only the diffrence? You need to add the diffrence relative to position. Fiddle

$(document).ready(function(){
    $('#test').bind('mousedown', function (e) {
        $(document).bind('mousemove', function (e) {
            var diff = e.pageX - $('#test').offset().left;
            $('#test').css('left', (diff+$('#test').offset().left) + 'px'); 
            //You need to remove it the mouse offset plus the diffrence, not to the diffrence between the previous position and the offset-
            // that'd just leave you rotating left and right between the position you want and the negative,
            // Since the diffrence changes each time you move on mousedown
        });
    });

    $(window).bind('mouseup', function (e) {
        $(document).unbind('mousemove');
    });
});

Upvotes: 0

rrk
rrk

Reputation: 15846

DEMO

$(document).ready(function(){
    $('#test').on('mousedown', function (e) {
        $this = $(this);
        $(document).bind('mousemove', function (e) {
            var left = e.pageX - ($this.width()/2);
            var top = e.pageY - ($this.height()/2);
            $('#test').css({
                'left': left + 'px',
                'top': top + 'px'
            });
        });
    });
    $(window).on('mouseup', function (e) {
        $(document).unbind('mousemove');
    });
});
#test {
    width: 300px;
    height: 60px;
    background-color: #333;
    position: absolute;
    top: 0;
    left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="test"></div>

Upvotes: 2

Related Questions