JQuery UI has a function called stop , and where you want to handle all calculations as such:
stop: function(event, ui) { // Object dragged var e = ui.helper; // Offset of that object var eOffset = e.offset().left; // Sliders offset var sliderOffset = sliderDiv.offset().left; // Subtract their offsets var totalOffset = eOffset - sliderOffset; // Width of box dragged var boxWidth = ui.helper.width(); // Subtract their widths to account for overflow on end var sliderW = sliderDiv.width() - boxWidth; // Get percent moved var percent = totalOffset / sliderW * 100; // Find .slider-value and replace HTML e.find(".slider-value").html(Math.round(percent)); }
It will be located here:
$(divs).draggable({ containment: '#content', cursor: 'move', snap: '#ratingBar', revert: function(event, ui) { $(this).data("uiDraggable").originalPosition = { top: 0, left: 0 }; return !event; }, .... <-- HERE });
I have provided comments for each line so you understand what I did.
Above your draggable function, you need to define a denser scope of protection:
var left = sliderDiv.offset().left; var right = left + sliderDiv.width(); var top = sliderDiv.offset().top; var bottom = top + sliderDiv.height(); var height = $(".itemContainer").height(); var width = $(".itemContainer").width(); $(divs).draggable({ containment: [left, 0, right - width, bottom - height], ..... });
This will prevent draggable from moving left, right or under the slider.
Basically, you capture the position of the captured object, adjust some offset, adjust for a certain width, calculate the percentage and replace html (you can also use text() ).
Here is your plunker redone: http://plnkr.co/edit/3WSCo77c1cC5uFiYO8bV?p=preview
Documentation:
Jquery user interface
Jquery.find