Smetad Anarkist
Smetad Anarkist

Reputation: 898

How to get the value of a jquery slider to follow the handle, but not all the way?

I have a jQuery slider that is supposed to be placed in a narrow column on a page. The idea is that the value should follow the handle in a tooltip like fashion underneath the slider. I've gotten that to work pretty good by using the pageX attribute of the "event object" in the jquery slider slide event.

$(element).css("left", event.pageX - ($(element).width() / 2)).text(ui.value);

But the problem is that due to the fact that the column in quite narrow so when I drag the slider to max the displayed value will be placed outside the column. Or a part of it will anyway.

The solution I've come up with is either make the slider shorter. But my designer will probably complain. The other solution is to make sure that the value I'm displaying have a narrower field of movement than the slider. But I'm not sure how to accomplish this.

Any suggestions on how I can get my value to neatly follow the handle. But in a way that it won't "fall out"?

EDIT: Here is a jsFiddle that explains how my situation looks today. The value that follows along on the bottom ends up outside the width of the column. That I've represented with a blue box.

http://jsfiddle.net/nuPYa/2/

Upvotes: 0

Views: 849

Answers (2)

DarthJDG
DarthJDG

Reputation: 16591

When calculating the position, you can easily force limits:

// Caching jQuery objects
var $element = $(element).text(ui.value);
var $container = $element.parent();

// Calculating new position
var newpos = event.pageX - $element.width() / 2;
newpos = Math.max(newpos, 0);
newpos = Math.min(newpos, $container.innerWidth() - $element.outerWidth());

$element.css('left', newpos);

The calculation was broken up for readability. The code above assumes that the main column container is the parent of your element.

Upvotes: 2

Aaria Carter-Weir
Aaria Carter-Weir

Reputation: 1679

First cache your $ object.

$element = $(element);

Then, instead of using the event.pageX attribute, use $element.position().left. Remember this is relative to the parent relative element. So you may want to use $element.offset().left

Upvotes: 0

Related Questions