Show DevBest iOS Range Toggle Sliders

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
I on Codepen and wanted to see if I could replicate the famous toggle-sliders we're all familiar with that use cleverly-styled checkboxes, instead of using range sliders like Marcus suggests for UI purposes.

TL;DR of the Codepen post: author wants to be able to actually drag the toggle-button rather than just click it



HTML
HTML:
<div class="range-toggles">
    <input type="range" class="range-toggle" value="0" min="0" max="1" />
    <input type="range" class="range-toggle" value="0" min="0" max="1" />
    <input type="range" class="range-toggle" value="1" min="0" max="1" />
    <input type="range" class="range-toggle" value="0" min="0" max="1" />
    <input type="range" class="range-toggle" value="1" min="0" max="1" />
</div>

JavaScript
JavaScript:
document.querySelectorAll('.range-toggle').forEach(function(el, i) {
    if (el.value === '1') el.classList.add('active'); //for sliders that are value=1 on page load

    el.addEventListener('mousedown', function(e) {
        var hasDragged = !1,
        initVal    = el.value;

        el.onmousemove = function() {hasDragged = 1;}

        el.onmouseup = function(e) {
            !hasDragged && (el.value = el.value==='1' ? '0' : '1');

            (initVal != el.value) && el.classList.toggle('active');
            hasDragged = !1;
        }
    });
});

SCSS
SCSS:
@mixin range-thumb() {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  background-color: #fff;
  border-radius: 25px;
  box-shadow: 0 2px 6px 2px rgba(50, 50, 50, .2);
  cursor: pointer;
  pointer-events: all;
  transition: width .15s ease-in-out;
}

.range-toggle {
  -webkit-appearance: none;
  appearance: none;
  width: 48px;
  height: 25px;
  outline: none;
  background-color: #fff;
  border: 2px solid #e6e6e6;
  border-radius: 25px;
  transition: all .3s cubic-bezier(0.61, -0.1, 0, 1.49);
  pointer-events: none;

  &.active {
    background-color: #4dde5e;
    border-color: #4dde5e;
  }

  &::-webkit-slider-thumb {
    @include range-thumb();
  }

    &:active::-webkit-slider-thumb {
      width: 30px;
    }

  &::-moz-range-thumb {
    @include range-thumb();
  }

    &:active::-moz-range-thumb {
      width: 30px;
    }
}

/* helper styles */
body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font: 400 15px/1.6 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
  flex: none;
  max-width: 700px;
  text-align: center;
}

.range-toggles {
  display: flex;
}
Post automatically merged:

Updated pen and post to reflect better post. Shouldn't really be any bugs now.
Post automatically merged:

Updated again to behave more like iOS toggles; removed the grey border on 'active' state, toggle width on click/mousedown
 
Last edited:

Users who are viewing this thread

Top