Ace
Ace

Reputation: 1146

Adjusting the range of a slider based on handle positions

I have a nouislider component with two handles. The handles represent start and end dates, using timestamps as values. Everything works as expected. I would just like to add a feature where moving the handles will scale the slider by changing the range.

Here's what my slider looks like. My Slider

I would like to have it so that, for instance, moving the left handle closer to the right will increase the lower range so that the area between the two handles is a greater percentage of the entire space. Kind of like a zooming effect.

I know how to update the range when I need to, I'm just wondering if there is some existing formula or general method of calculating such a thing, where the position of the handles will dictate the range; perhaps something using the distance between the left handle and the min range, and vice versa.

Upvotes: 0

Views: 302

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

One possible way would be to define the lower and upper bounds such that the handles will always be at fixed percentages of the total range. E.g.:

lh, rh := left handle and right handle values
lower, upper := lower and upper bounds of the range
tl, tr := percentages of left and right handles:

Then you want to solve the linear system

lh = (1 - tl) * lower + tl * upper
rh = (1 - tr) * lower + tr * upper

The solution of that is:

lower = (lh * tr - rh * tl) / (tr - tl)
upper = (rh - lh + lh * tr - rh * tl) / (tr - tl)

If you want to use tl = 0.25 and tr = 0.75, you would get:

lower = 1.5 * lh - 0.5 * rh
upper = 1.5 * rh - 0.5 * lh

You can then clamp the range to your min and max values.

Upvotes: 1

Related Questions