Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Draggable Containment Overflow Hidden

This is about dragging wider element than its parent (overflow: hidden). Parent's width and overflow options are fixed, cannot be changed.

HTML

<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</div>

CSS

.container {
  position:relative;
  width:300px;
  height:50px;
  background:#ccc;
  overflow:hidden; // be careful, changing to overflow-x:hidden breaks the answer
}
.text {
  position:absolute;
  top:7px;
  margin:0;
  width:1000px;
  font-size:30px;
}

jQuery

$('.text').draggable({
  axis: 'x',
})

Modify this demo: https://jsfiddle.net/jeafgilbert/LtkkzccL/

So that we can only drag the sentence without making spaces before or after the sentence.

like image 598
Jeaf Gilbert Avatar asked Feb 14 '16 17:02

Jeaf Gilbert


1 Answers

You can check the current position of draggable element in the drag callback and then override the position if it is outside of the bounds.

In other words, if the left positioning is greater than 0, override the left positioning and set it back to 0 so that it can never exceed 0. If the width of the draggable element minus the width of the parent element is less than the left positioning, override the left positioning to set it back to the offset width.

Updated Example

$('.text').draggable({
  axis: 'x',
  drag: function(event, ui) {
    var left = ui.position.left,
        offsetWidth = ($(this).width() - $(this).parent().width()) * -1;

    if (left > 0) {
      ui.position.left = 0;
    }
    if (offsetWidth > left) {
      ui.position.left = offsetWidth;
    }
  }
});
.container {
  position: relative;
  width: 300px;
  height: 50px;
  background: #ccc;
  overflow: hidden;
}
.text {
  position: absolute;
  top: 7px;
  margin: 0;
  white-space: nowrap;
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="container">
  <p class="text">The quick brown fox jumps over the lazy dog.</p>
</div>
like image 67
Josh Crozier Avatar answered Sep 29 '22 17:09

Josh Crozier