ps0604 ps0604 - 5 months ago 35
jQuery Question

Jquery UI draggable changing the size of other divs

In this plunk I have a div between two other divs. The div in the middle can be dragged up and down (with Jquery Draggable) to resize the height of the two other divs. However there's a strange behavior, the div that is dragged does not follow the mouse, and you can see two divider lines. How to fix this?

HTML

<div id="top1"></div>
<div id="div1"></div>
<div id="bottom1"></div>


Javascript

var top1H, bottom1H;
$( "#div1" ).draggable({
axis: "y",
start: function() {
top1H = $("#top1").height();
bottom1H = $("#bottom1").height();
},
drag: function(event,ui) {
var shift = ui.position.top;
$("#top1").height(top1H + shift);
$("#bottom1").height(bottom1H - shift);
}
});


CSS

#div1 {
width:180px;
height:6px;
background-color:#e0e0e0;
cursor:ns-resize;
}
#top1{
width:180px;
height:100px;
background-color:orange;
}
#bottom1 {
width:180px;
height:100px;
background-color:blue;
}

Answer

I was able to get the effect you want by making some small changes to the height calculations.

Here's an updated Plunker

The main change was to the height calculation:

$( "#div1" ).draggable({
  axis: "y",
  start: function(event, ui) {
    shiftInitial = ui.position.top;
    top1H = $("#top1").height();
    bottom1H = $("#bottom1").height();
  },
  drag: function(event,ui) {
    var shift = ui.position.top;
    $("#top1").height(top1H + shift - shiftInitial);
    $("#bottom1").height(bottom1H - shift + shiftInitial);
  }
});

enter image description here