Eugen Eray
Eugen Eray

Reputation: 113

How to create a floating element over input type range

I need span#a to translate to the same position on where slider thumb is. I need to somehow use transform: translateX(and_step_to_translate_here). So to say a bit easier, I need span#a to follow the track thumb. How can I do it?

input {width: 90%;}
<input type="range" min="0" max="100" step="1"/><br/>
<span id="a">I'm following.</span>

Upvotes: 1

Views: 981

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

What I can suggest is to use input range oninput event to follow the value of the input and use a proportional margin-left with this value.

Here's the code you need:

$('input[type="range"]').on('input', function() {
  $('span#a').css('margin-left', parseInt($(this).val() - 10) > 0 ? parseInt($(this).val() - 10) + '%' : '0px');
});

Demo:

$('input[type="range"]').on('input', function() {
  $('span#a').css('margin-left', parseInt($(this).val() - 10) > 0 ? parseInt($(this).val() - 10) + '%' : '0px');
});
input {
  width: 90%;
}

span#a {
  display: block;
  width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="0" max="100" step="1" value="0" />
<span id="a">I'm following.</span>

Note:

  • This will update the span left margin to be proportional to value of the range, so it will be updating between 0% to 100%, which gives it the floating effect.

  • In the following sample Demo, the margin-left value needs more
    adjusting so it will give a better result. The logic is there, but
    needs just some adjustment.

Upvotes: 1

Yudi Chang
Yudi Chang

Reputation: 448

https://jsfiddle.net/2cc83shx/2/

$( document ).ready( function() {
    $( '#rangeInput' ).on( 'change', function() {
        $( '#a' ).css({
            'transform': 'translateX(' + $(this).val() + 'px)'
        })
    })
})

I can help a bit. you can positioning it a bit better later from my fiddle. (here, I'm using jquery to select the element. you can use pure js to do this too)

*UPDATE

If you want it to follow whenever you drag the range, follow the code below

https://jsfiddle.net/2cc83shx/3/

Upvotes: 1

Related Questions