1

I try to made a custom scrollbar using the drag&drop/draggable function in JQueryUI

I made this JSFiddle:

http://jsfiddle.net/96k2ysbf/1/

HTML

<div id="scrollbar-zone" class="w85pc">
  <div id="scrollbar" style=""></div>
</div>

CSS

.w85pc{
  width: 80%;
  margin: 0 auto;
}

#scrollbar-zone{
    border: 1px solid black;
    height: 30px;
}

#scrollbar{
    border: 1px solid red;
    height: 100%;
    width: 10px;
}

Javascript

$("#scrollbar").draggable({
    axis: "x",
    containment: 'parent'
});

It works fine, but sometimes when I resize the window, the draggable object goes outsite the parent element, and I want to avoid that.

What's the easiest way to fix this problem? I could use the resize() event but there's maybe a better solution.

Pascal Goldbach
  • 977
  • 1
  • 15
  • 34

1 Answers1

3

You can convert the position to percentage on stop event, so when resizing the scrollbar will keep its proportional position. Like this:

$("#scrollbar").draggable({
  axis: "x",
  containment: 'parent',
  stop: function(e, ui) {
    var perc = ui.position.left / ui.helper.parent().width() * 100;
    ui.helper.css('left', perc + '%');
  }
});

http://jsfiddle.net/axmgm2j2/

Julien Grégoire
  • 16,864
  • 4
  • 32
  • 57