Asp.Net : Apply jQuery UI slider to create a scrollable div

Leave a Comment

The slider control is useful in various applications requiring user interaction such as volume control, color pickers, etc. In this article, we will apply the jQuery UI slider widget to create a scrollable div.

Create a new web form Slider.aspx and add the below code.
<form id="form1" runat="server">
<div align="center" >
<div id ="slider"></div>
<div id="outerContent">
<div id="innerContent">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum
</div>
</div>
</div>
</form>

Let's take a look at the adopted approach for scrolling the inner div based on the position of the slider:

  1. First determine the amount of scrollable area available:
    Scrollable Area = (Width of Inner Div) – (Width of Outer Div)
  2. Now, apply the Slider value to this Scrollable area to get the left scroll position:
    Left Scroll Position= (Slider Value * Scrollable Area)/100
  3. Since, the slider value is a percentage, in the above formula we divide by 100.
  4. Now, set the scrollLeft property of the outer div to the above value to scroll the inner div as per the slider.


Next, let's use jQuery UI to implement the slider
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#slider").slider({
min: 0,
max: 100,
animate: true,
slide: function(e, ui) {
var iScrollWidth = $("#innerContent").width() -
$("#outerContent").width();
$("#outerContent").attr({ scrollLeft: (ui.value *
0.01 * iScrollWidth) });
},
change: function(e, ui) {
var iScrollWidth = $("#innerContent").width() -
$("#outerContent").width();
$("#outerContent").animate({ scrollLeft: (ui.value
* 0.01 * iScrollWidth) }, "slow");
}
});
});
</script>

0 comments:

Post a Comment