Search code examples
jqueryhtmlcssjquery-uijquery-ui-slider

How do I stop the jquery UI slider from sliding beyond the container


I am using jQuery UI horizontal slider. I need the position of the handle to be always within the slider. If I set the margin-left to minus of handle's width, the right position is within the container but the left position moves out of the container. I want to achieve this with CSS only. I don't want to add any wrapper div.
The following is the HTML code:

<div id="slider"></div>
<ul id="box">
  <li>Fade with the above slider...</li>
  <li>Fade with the above slider...</li>
</ul>

The CSS is as follows:

#box {
  width: 200px;
  height: 200px;
  background-color: #ff0000;
}

#slider {
  width: 200px;
}

.ui-slider .ui-slider-handle {
  width: 20px;
  margin-left: -10px;
}

Finally, the js code:

$(document).ready(function() {
 $('#slider').slider({
   min: 0,
   max: 1,
   step: 0.1,
   value: 1
 })
 .bind("slide", function() {
   //get the value of the slider with this call
   var o = $(this).slider('value');
   $(e).css('opacity', o)
 });
});

enter image description here

Any help will be appreciated.


Solution

  • $("div").slider();
    section {
      margin: 1em;
      border: 1px dotted red;
    }
    
    h1 {
      margin: 0;
    }
    
    div {
      margin: .3em .6em;
    }
    
    .new .ui-slider:before {
      content: "";
      background: inherit;
      border: inherit;
      border-radius: inherit;
      position: absolute;
      left: -.6em; /* Half of the handle width */
      top: -1px; /* Width of the border */
      right: -.6em;
      bottom: -1px;
    }
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    
    <section>
      <h1>Default</h1>
      <div></div>
    </section>
    
    <section class="new">
      <h1>Modified</h1>
      <div></div>
    </section>