Apurva
Apurva

Reputation: 527

drag and drop into a scrollable div

So I have created a very short drag and drop program which works however there is a small glitch.

created a js fiddle here just to show you the issue I am facing

As you can see you are able to drop the cards into the dotted slots. the problem occurs when one moves the scroll bar of the div (that contain the slots). The cards do not seem to stick with the dotted slots. Now I am assuming it si due to absolute and relative position. I have tried changing them but it creates more issues. i have also tried the offset method where by when the div is scrolled it calculates the offset of the slots and then uses those offsets to to position the cars. It doesn't work too well either. the code is given below.

$('#dropdiv').scroll(function() {
    var p = $( "#answerone" );
    var position = p.offset();
    console.log( "leftoffset: " + position.left + ", top: " + position.top );
    var position3 = p.position();
    console.log( "leftpos: " + position3.left + ", top: " + position3.top );
    // ui.draggable.addClass( $(this).attr('id') );
    $("#card1").draggable( 'enable' );
    // $("#card1").droppable( 'enable' );
    // $("#card1").draggable.position( { of: $("#card1"), my: 'left top', at: 'left top' } );
    $("#card1").draggable( 'option', 'revert', false );
    var position2 =  $("#card1").offset();
    console.log( "left2222: " + position2.left + ", top: " + position2.top ); 
    var toppos=position.top-position2.top;
    console.log("div position.top  - "+position.top );
    console.log("element position2.top - "+position2.top);
    console.log("relativvtop - "+toppos);
    // console.log("scrollTop - "+$("#dropdiv")scrollTop());
    $("#card1").css( {postion:'absolute',top: toppos+'px'});
});

edit1: if i dont have a scrollable div then it works perfectly. but for some design reasons i need the scrollable div.

what am i doing wrong. how do i fix it. Any help is appreciated.

Upvotes: 1

Views: 1924

Answers (1)

Twisty
Twisty

Reputation: 30903

You'll want to do some cleanup, but basically, when you drop the item, it never attaches to any of the content that is being scrolled.

For example, you could replace:

 ui.draggable.position({
   my: 'left top',
   at: 'left top',
   of: $(this)
 });

With:

 ui.draggable.css({
   top: "",
   left: ""
 }).appendTo($(this));

Your first piece of code simply sets the position of the item. When you scroll, that item remains in that position based on it's top and left.

Example: http://jsfiddle.net/Twisty/x0fmgxaz/1/

This results in HTML of the following:

<div id="answerone" class="cardSlots answer ui-droppable" style="margin: 0 auto;display:block;float: none;" aria-disabled="false">
  <div id="card2" class="cardname ui-draggable answerone animated pulse" style="position: relative; z-index: 5;" aria-disabled="false">
    2
  </div>
</div>

Hope that helps.

Upvotes: 1

Related Questions