views:

22

answers:

2

Hello,

How to restrict drag (disable) in the block? Full example

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript">
    $(function(){
        var x = 0, setElementMove = 0, getElementMove = $('#drag');
        getElementMove.mousedown(function(event){
            x = event.clientX+$(document.body).position().left-parseInt($(this).css('left'));
            setElementMove = true;
            if(typeof event.preventDefault != 'undefined'){
                event.preventDefault();
                return false;
            }
        });
        getElementMove.ondragstart = function(){
            return false;
        };
        $(document).mouseup(function(){
            setElementMove = false;
        });
        $(document).mousemove(function(event){
            if(setElementMove){
                getElementMove.css('left', event.clientX+$(document.body).position().left-x + 'px');
            }
        });
    });
    </script>

<h1>How to restrict drag (disable) in the block?</h1>
<div id="block">
    <div id="border">
         <div id="drag" style="left:200px;">some text</div>
    </div>
</div>

<style type='text/css'>
h1, #drag {
    font: bold 1.0em arial, helvetica, tahoma, verdana, sans-serif;
    margin: 10px 0px;
    text-align: center;
}
#block {
    border: 1px solid #DDD;
    overflow: hidden;
    width: 100%;
}

#border {
    border: 1px solid red;
    margin: 0px auto;
    overflow: hidden;
    width: 70%; /*important*/
    height: 150px;
}

#drag {
    background: #DDD;
    cursor: default;
    position: absolute;
    top: 50px;
    width: 54px;
    height: 45px;
}
</style>
A: 

Since you asked for jQuery (altough you are using Mootools in your example), have a look at jQuery Ui Draggable. They have IMO the best drag & drop utility you can have with jQuery.

Tim
No- the OP is using jQuery, you can see it on top of his code `<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>`
Reigel
Oops, yeah, you're right. I'm sorry, just saw the used library in jsfiddle.
Tim
+2  A: 

edit your mousemove like this,

$(document).mousemove(function(event) {
    var eleft = event.clientX + $(document.body).position().left - x;
    if (eleft > boundary.offset().left && (eleft + getElementMove.width() < boundary.offset().left + boundary.width() ) ) {
        if (setElementMove) {
            getElementMove.css('left', eleft + 'px');
        }
    }
});

crazy demo

Reigel