tags:

views:

32

answers:

1

Hi,

I have a nice working slider script (no libraries used). I need a math concept that would allow the slider to perform a callback on a specified pixel interval. So for example, my slider is 300px wide, and I specify the interval=10, then when the user slides the handle, the callback should happen at pixel positions 10,20,30,40 and so on. If the interval=3 then the callback should happen at pixel positions 3,6,9,12...etc. It's the math formula that I am looking for specifically. Any help would be appreciated.

Pat

A: 

So say you have the variables:

var width = 300;   // px
var interval = 10; // px
var pos; // current position

And then you should do:

if ( pos % interval === 0 ) 
  // do stuff

This is called modulus operator which returns the remainder of dividing left_var by right_var. If the remainder is 0 your check will return true, and so you do the callback (exactly at pixel 10, 20, 30, 40, etc.).

But please note that it's very naive to think that you will be able to handle every pixel change... What I'd rather do is to examine if the slider has entered to a given segment.

var segment = 1;

Then after the state of the slider changes you check for position like this:

if ( Math.floor( pos / interval ) === segment ) {
  // do stuff because the slider
  // has entered a new segment
  // ...
  segment++;
}

If the slider moves backwards and you want to fire the events accordingly just decrement the segment instead of incrementing.

galambalazs
Thank you for your good advice on this issue. Both methods work well. You indicated that you would prefer the segment method. The only thing I should probably do differently is instead of using math.floor, use a n|0 or n|n bit shift for better speed, correct?
cube
Won't make much of a difference. Javascript is rarely the bottleneck of performance. You should care for touching the DOM as little as possible instead, and then things will go fast. Good luck! And if you like the answer you may want to accept it: http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about/5235#5235
galambalazs
Thanks, and sorry about not accepting. I guess you can tell that I am new to the site.
cube
No problem at all! That's why I gave you the link. Welcome at SO! :)
galambalazs