Question

I am having trouble setting the containment value of the jqueryUI draggable function when using the [x1,y1,x2,y2] format. Here is the js:

<script type="text/javascript">
    //slideTest.js
    $(document).ready(function(){
        $('.slideMin').each(function(){
            $(this).draggable({
                containment: [$(this).parent().offset().left,$(this).parent().offset().top,$(this).next('div').offset().left,$(this).parent().offset().top]
            });
        });
</script>

And the html which the script is interacting with:

<div class="slideBar">
    <div class="slideMin"></div>
    <div class="slideMax"></div>
</div>

I am trying to set the drag containment (of the slideMin div) based on the offset().left of the next div, in this case (slideMax).

In other words, I want the draggable behavior to stop (for the slideMin div) when it reaches the left of the next (slideMax) div.

The x1 seems to be working as the drag is stopping at the position defined, however, it is overlapping and extending beyond the next div, which i do not want to happen. There must be something wrong with how I am setting the x2 value but I am not sure what it is.

Any advice?

Was it helpful?

Solution

Figured it out... I had two divs, both draggable. The first div was to stop when it reached the next div. The above code accomplished this until I was to drag either div: once either div was dragged, the draggable range for the other div was not updating, therefore, I received the error where the draggable range was overlapping the other div. To fix it, I had to re-initiate and set the draggable range for the other div within the draggable function for the div that was being moved.

The new code goes something like this:

$(this).draggable({
    containment: [$(this).position().left, $(this).position().top, $(this).next().position().left - $(this).width()+4, $(this).position().top],
    drag: function(e){
        $(this).next().draggable({
            containment: [parseFloat($(this).position().left) + parseFloat($(this).width())-4, $(this).next().position().top, parseFloat($(this).parent().position().left) + parseFloat($(this).parent().width())-3, $(this).next().position().top]
        });
    }
});
$(this).draggable({
    containment: [parseFloat($(this).prev().position().left) + parseFloat($(this).prev().width())-4, $(this).position().top, $(this).position().left, $(this).position().top],
    drag: function(e){
        $(this).prev().draggable({
            containment: [$(this).parent().offset().left-$(this).prev().width()+5, $(this).prev().position().top, $(this).position().left - $(this).prev().width()+4, $(this).prev().position().top]
        });
    }
});

PS, the numbers -3 -4 +5, etc. were to add spacing for the handles on my draggable divs (4px handles), if you don't have handles you don't need the extra -3 -4 +5 portions of the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top