Search code examples
jquery-uijquery-draggable

Dragging is flickery when containment's overflow property is scroll?


I want to make an element draggable in a fixed area that has its overflow property set to scroll.

If I use containment property in the draggable element, then the dragging downwards or to the right becomes flickery. What I mean by this is that when the edge of dragged element hits the edge of the container, it does not scroll until the cursor hits the edge as well.

I can prevent this by not setting the containment property on the draggable setup. However when I drag to the left or top, the dragged element becomes invisible by being dragged to some negative x/y position.

How can I prevent the flicker when using containment property?

Plunkr -> http://plnkr.co/edit/pmGO6lswaSJtwMSC1bXe?p=preview

#container {
    border:1px solid red; 
    min-height:3in;
    overflow:scroll;
    margin-left:120px;
}

.widget {
    background: beige;
    border:1px solid black;
    height: 100px; width:100px;
}



<div id="container">
     <div class="widget"></div>
</div>



$(function(){
  $('.widget').draggable({
    scroll:true,
    containment: '#container' // comment out to see the smoothness on bottom/right edge drags
  });
})

Solution

  • Fixed it with this

    $(function(){
      $('.widget').draggable({
        scroll:true,
        drag:function(evt, obj) {
          if (obj.position.top < 0) {
            obj.position.top = 0;
          }
          if (obj.position.left < 0) {
            obj.position.left = 0;
          }
        }
      });
    })
    

    Inspired by answer to this question -> jQuery UI draggable, stop drag but let dragging the other way