Wednesday, 18 December 2013

Using client side Javascript to show the current selected value on a slider

We have recently been asked to create a webpage that has multiple sliders created dynamically using php. Not a problem, but we then asked if we could show the selected value as the slider was moved. Using hints from the following websites we managed to do it using a few extra lines of code:

http://snipplr.com/view/3624/ - This gave us a starting point for showing the floating values
http://javascript.info/tutorial/coordinates - This was needed to fix any issues with the page being scrolled

So to the code, the script below is an overview of how it works.

1:  <head>  
2:  <style>  
3:  #sliderVal {  
4:    display:none;   
5:    position:absolute;   
6:    border-style: solid;   
7:    background-color: white;   
8:    padding: 5px;  
9:    }  
10:  </style>  
11:  <script type="text/javascript" language="JavaScript">  
12:       function ShowContent(item) {  
13:            var dd = document.getElementById('sliderVal');  
14:            var rect = item.getBoundingClientRect();  
15:            var body = document.body  
16:            var docElem = document.documentElement  
17:            var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop  
18:            var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft  
19:            var clientTop = docElem.clientTop || body.clientTop || 0  
20:            var clientLeft = docElem.clientLeft || body.clientLeft || 0  
21:            var top = rect.bottom + scrollTop - clientTop  
22:            var left = rect.left + scrollLeft - clientLeft  
23:            dd.style.left = left + "px";  
24:            dd.style.top = top + "px";  
25:            dd.style.display = "block";  
26:            dd.innerHTML = item.value;  
27:       }  
28:  </script>  
29:  </head>  
30:  <body>  
31:  <div id="sliderVal"> </div>  
32:  <form>  
33:  0<input onchange="javascript:ShowContent(this)" type="range" name="slider1" ID="slider1" min="0" max="9">9<br />  
34:  0<input onchange="javascript:ShowContent(this)" type="range" name="slider1" ID="slider1" min="0" max="9">9<br />  
35:  </form>  
36:  </body>  

Lines 2 to 10 setup the style for the floating value (sliderVal), but lines 11 to 28 is the Javascript that does all the work. The Javascript is set to run when any of the sliders change. Firstly the sliderVal element is grabbed, then lines 14 to 22 calculate the position of the slider on the page. The position of the sliderVal element is then set, and it is shown. Lastly the text of the sliderVal element is set to the value of the slider.

No comments:

Post a Comment