notes and other stuff

 
« Back to blog

How to make a useful slider in 30 lines of javascript

I was looking a bit at yui slider packet, and it seems todo way too much. I am one of these crasy people that like to know how my code works and after look at yui code base, I decided it was too much for just a simple little slider.
 
Naturally js-frames are perfect if you just want something quick and dont think its fun to deal with cross browser issues. As I have come to know javascript better, I prefer to avoid all these frameworks.
I just want something that is easy to change/maintain/simple and doesnt have to many dependency.
 
So I decide to spend a little hour to create a simple slider that does what i want. It ended up just below 30 lines of javascript.
 
The HTML :

<div id="volumeBar" class="volumeBar">
<div id="volumeSlider" class="volumeSlider">

The Javascript:
 
 

  var volumeBar = document.getElementById('volumeBar'); 
 
     var slider = document.getElementById('volumeSlider'); 
 
     var getPosition = function(el) { 
       var curLeft = curTop = 0; 
       while(el) { 
         curLeft += el.offsetLeft; 
         curTop += el.offsetTop; 
         el = el.offsetParent; 
       } 
       return {left : curLeft, top : curTop}; 
     } 
 
     volumeBar.onmouseup = function(e) { 
       volumeBar.onmousemove = null; 
       var event = e || window.event; 
       var volLeft = getPosition(volumeBar).left; 
       var width = volumeBar.offsetWidth; 
       slider.style.width = (event.clientX - volLeft)/width * 100 + 'px'; 
     }; 
 
     volumeBar.onmousedown = function() { 
       var volLeft = getPosition(volumeBar).left; 
       var width = volumeBar.offsetWidth; 
       document.onmouseup = function() { 
         document.onmouseup = null; 
         volumeBar.onmousemove = null; 
       }; 
       volumeBar.onmousemove = function(e) { 
         var event = e || window.event; 
         slider.style.width = (event.clientX - volLeft)/width * 100 + 'px'; 
       }; 
       return false; 
     };


Comments (0)

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     Connect     twitter