Drag Div

Dragging div based on mouse move and restricting it within a container

by kapilgopinath

HTML

<div><div class="container">
    <div class="slider"/>
    </div>
</div><br/>
<div class="container">
    <div class="slider"/>
</div>

CSS

.container{
    position:relative;
    border:1px solid red;
    height:100px;
}
.slider{
    height:99px;
    width:20px;
    background:green; 
    position:absolute;
}

JavaScript

$(function() {
    $('.slider').slider();
});

$.fn.slider = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css('left', 0);
        var dragging = false;
        var startX = 0;
        var startL = 0;
        $el.mousedown(function(ev) {
            dragging = true;
            startX = ev.clientX;
            startL = $el.css('left');
        });
        $(window).mousemove(function(ev) {
            if (dragging) {
                // calculate new left
                var newLeft = parseInt(startL) + (ev.clientX - startX);
                
                //stay in parent
                var maxLeft =  $el.parent().width()-$el.width();          
                newLeft = newLeft<0?0:newLeft>maxLeft?maxLeft:newLeft;
                $el.css('left', newLeft );
            }
        }).mouseup(function() {
            dragging = false;
        });
    });
}