Search code examples
javascripthtmljquery-slider

Align text with a slider


I have a table structure like this

<tr>
    <td>
      Text to move
    </td>
</tr>
<tr>
    <td>
       <div>jQuery slider container is in here<a>slider pointer is in here</a></div>
    </td>
</tr>

When the slider moves I see the style is updated for the link element by a percentage representing how far to the right it is Ex: style="left: 11.7647%;" I want "text to move" to align itself with the slider, and also move by that percentage. Is there any way I can do this? I can add more divs/spans etc. if necessary.

Note: I know how to grab the percentage the slider has moved, the issue is just aligning it.


Solution

  • Since you already know the percentage, you can set the text to have a left margin of that same percentage:

    $("#hoverText").css("margin-left", percent + "%");
    

    Here's my working test code:

    HTML

    <table id="layoutTable" style="width:100%;">
      <tr>
        <td>Percent: <span id="percent"></span></td>
      </tr>
      <tr>
        <td style="width:100%;"><span id="hoverText">Here's Some Text</span></td>
      </tr>
      <tr>
        <td style="width:100%;"><div id="slider"></div></td>
      </tr>
    </table>
    

    JavaScript

    $(document).ready(function(){
      $("#slider").slider({
        "slide": function(event, ui) {
          var percent = ui.value;
          $("#percent").html(percent);
          $("#hoverText").css("margin-left", percent + "%");
        }
      });
    });