jQuery Draggable Child Containment

Viewed 43

I am using the jQuery-ui library to drag an image/child within a parent container. In theory, I'm trying to replicate the bounds of a webpage in a browser. I want to:

  1. If the child bottom reaches the parent bottom, I want to prevent further dragging upwards on y-axis.
  2. If the child top reaches the parent top (which is the initial position on page load), prevent dragging downwards on y-axis.

A quick CodePen to help illustrate where I'm at: https://codepen.io/austin-branham/full/eYGgoNg

My script:

var draggableHeight = $('.draggable').height();
var parentHeight = $('.project-image').height();

$('.draggable').draggable({
  axis: "y",
  drag: function(e, ui) {
    // figure out how far to drag within this function
  }
});
1 Answers

I was able to work through how to prevent the child from continuing to drag once it's bottom had met the bottom of the parent. The diff variable has - 75 due to my 75px margin in my design. For anyone else, that would be a variable that needs to be defined. Solution here:

  var drag = $('.draggable')
  drag.draggable({
    axis: "y",
    drag: function(e, ui) {
      var parentHeight = $('.project-image').height(),
          childHeight = drag.height(),
          diff = childHeight - parentHeight - 75
          
      if (ui.position.top > 0) {
        ui.position.top = 0;
      }
      if (ui.position.top <= '-' + diff) {
        ui.position.top = '-' + diff;
      }
    },
    scroll: false
  });
Related