Search code examples
jquerycssjquery-uiuislider

How to stop handle over hanging the slider?


I'm using jQuery Slider with a custom handle.

My handle is quite large and this means that if you drag it all the way to the right then it overhangs the end of the slider bar...

Using a method like:

margin-left:-50%;

Only works for when it's on the right hand side (100%) but if you move it left then the negative margin pulls it off screen for that side.

How to solve this whilst keeping it responsive? I'd like to get it so that the end of the handle/image is parallel to the end of each bar if that makes sense.

var handle = $("#custom-handle");
$("#slider").slider({
  create: function() {
    handle.text($(this).slider("value"));
  },
  slide: function(event, ui) {
    handle.text(ui.value);
  }
});
#custom-handle {
  width: 20%;
  background: transparent;
  height: 57px;
  background-image: url(https://s3-eu-west-1.amazonaws.com/quizdu/redslider.png);
  top: 0%;
  border: none;
  margin-top: -1.8em;
  background-size: 100%;
  text-align: center;
  line-height: 1.6em;
}

.container {
  max-width: 500px;
  margin: 0 auto;
}

body {
  padding-top: 50px;
  background: grey;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
  <div id="slider">
    <div id="custom-handle" class="ui-slider-handle"></div>
  </div>
</div>


Solution

  • If you translate the value into a percentage, and multiply that against the width of the handle you can use that as an offset

    var handle = $("#custom-handle"),
        handleWidth = handle.width();
    $("#slider").slider({
      create: function() {
        handle.text($(this).slider("value"));
      },
      slide: function(event, ui) {
        handle.text(ui.value);
        handle.css({
            'margin-left': 0 - ((ui.value / 100) * handleWidth)
        });
      }
    });
    #custom-handle {
      width: 20%;
      background: transparent;
      height: 57px;
      background-color: #0099ff;
      top: 0%;
      border: none;
      margin-top: -1.8em;
      background-size: 100%;
      text-align: center;
      line-height: 1.6em;
    }
    
    .container {
      max-width: 500px;
      margin: 0 auto;
    }
    
    body {
      padding-top: 50px;
      background: grey;
    }
    <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <div class="container">
      <div id="slider">
        <div id="custom-handle" class="ui-slider-handle"></div>
      </div>
    </div>