css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="swappy-radios" role="radiogroup" aria-labelledby="swappy-radios-label">
  <h3 id="swappy-radios-label">Select an option</h3>
  <label>
    <input type="radio" name="options" checked />
    <span class="radio"></span>
    <span>First option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Second option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Third option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Fourth option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Last option</span>
  </label>
</div>


            
          
!
            
              html { box-sizing: border-box; height: 100%; font-size: 10px; } *, *::before, *::after { box-sizing: inherit; }

body {
  display: flex; 
  align-items: center; 
  justify-content: center; 
  min-height: 100vh;
  color: #0f273d;
  font-family: 'Lato', sans-serif;
}

h3 {
  font-size: 2.5rem;
  font-weight: bold;
}

.swappy-radios {
  label {
    display: block;
    position: relative;
    padding-left: 4rem;
    margin-bottom: 1.5rem;
    cursor: pointer;
    font-size: 2rem;
    user-select: none;
    color: #555;
    &:hover input ~ .radio {
      //using opacity for hover effect, because background is used (amd delayed!) for the shuffle
      opacity: 0.8;
    }
  }
  input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
    &:checked {
      ~ span {
        color: #0bae72;
        transition: color .5s;
      }
      ~ .radio {
        background-color: #0ac07d;
        opacity: 1!important;
        &::after {
          opacity: 1;
          //applying in JS, so as not to make selections delayed when no js:
          // transition: opacity 0s 0.75s;
        }
      }
    }
  }
  .radio {
    position: absolute;
    top: 0;
    left: 0;
    height: 2.5rem;
    width: 2.5rem;
    background: #c9ded6;
    border-radius: 50%;
    &::after {
      display: block;
      content: '';
      position: absolute;
      opacity: 0;
      top: .5rem;
      left: .5rem;
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 50%;
      background: #fff;
      //applying in JS, so as not to make selections delayed when no js:
      // transition: opacity 0s 0.75s;
    }
  }
}

            
          
!
            
              let currentValue = 1;
const timeout = 0.75;
const radios = document.querySelectorAll('.swappy-radios input');
const fakeRadios = document.querySelectorAll('.swappy-radios .radio');

//This next bit kinda sucks and could be improved.
//For simplicity, I'm assuming that the distance between the first and second radios is indicative of the distance between all radios. This will fail if one of the options goes onto two lines.
//I should really move each radio independantly depending on its own distance to its neighbour. Oh well ¯\_(ツ)_/¯
//TODO ^^^
const firstRadioY = document.querySelector('.swappy-radios label:nth-of-type(1) .radio').getBoundingClientRect().y;
const secondRadioY = document.querySelector('.swappy-radios label:nth-of-type(2) .radio').getBoundingClientRect().y;
const indicitiveDistance = secondRadioY - firstRadioY;
//End suckyness :D

//Apply CSS delays in JS, so that if JS doesn't load, it doesn't delay selected radio colour change
//I'm applying background style delay here so that it doesn't appear slow if JS is disabled/broken
fakeRadios.forEach(function(radio) {
  radio.style.cssText = `transition: background 0s ${timeout}s;`;
});
//Have to do this bit the long way (i.e. with a <style> element) becuase you can't do inline pseudo element syles
const css = `.radio::after {transition: opacity 0s ${timeout}s;}`
const head = document.head;
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
//End no-js animation fallbacks.

radios.forEach(function(radio, i) {
  //Add an attr to make finding and styling the correct element a lot easier
  radio.parentElement.setAttribute('data-index', i + 1);
  
  //The meat: set up the change listener!
  radio.addEventListener('change', function() {
    //Stop weirdness of incomplete animation occuring. disable radios until complete.
    temporarilyDisable();

    //remove old style tag
    removeStyles();
    const nextValue = this.parentElement.dataset.index;

    const oldRadio = document.querySelector(`[data-index="${currentValue}"] .radio`);
    const newRadio = this.nextElementSibling;
    const oldRect = oldRadio.getBoundingClientRect();
    const newRect = newRadio.getBoundingClientRect();

    //Pixel distance between previous and newly-selected radios
    const yDiff = Math.abs(oldRect.y - newRect.y);
    
    //Direction. Is the new option higher or lower than the old option?
    const dirDown = oldRect.y - newRect.y > 0 ? true : false;
    
    //Figure out which unselected radios actually need to move 
    //(we don't necessarily want to move them all)
    const othersToMove = [];
    const lowEnd = Math.min(currentValue, nextValue);
    const highEnd = Math.max(currentValue, nextValue);

    const inBetweenies = range(lowEnd, highEnd, dirDown);
    let othersCss = '';
    inBetweenies.map(option => {
      //If there's more than one, add a subtle stagger effect
      const staggerDelay = inBetweenies.length > 1 ? 0.1 / inBetweenies.length * option : 0;
      othersCss += `
        [data-index="${option}"] .radio {
          animation: moveOthers ${timeout - staggerDelay}s ${staggerDelay}s;
        }
      `;
    });
    
    const css = `
      ${othersCss}
      [data-index="${currentValue}"] .radio { 
        animation: moveIt ${timeout}s; 
      }
      @keyframes moveIt {
        0% { transform: translateX(0); }
        33% { transform: translateX(-3rem) translateY(0); }
        66% { transform: translateX(-3rem) translateY(${dirDown ? '-' : ''}${yDiff}px); }
        100% { transform: translateX(0) translateY(${dirDown ? '-' : ''}${yDiff}px); }
      }
      @keyframes moveOthers {
        0% { transform: translateY(0); }
        33% { transform: translateY(0); }
        66% { transform: translateY(${dirDown ? '' : '-'}${indicitiveDistance}px); }
        100% { transform: translateY(${dirDown ? '' : '-'}${indicitiveDistance}px); }
      }
  `;
    appendStyles(css);
    currentValue = nextValue;
  });
});

function appendStyles(css) {
  const head = document.head;
  const style = document.createElement('style');
  style.type = 'text/css';
  style.id = 'swappy-radio-styles'; 
  style.appendChild(document.createTextNode(css));
  head.appendChild(style);
}
function removeStyles() {
  const node = document.getElementById('swappy-radio-styles');
  if (node && node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function range(start, end, dirDown) {
  let extra = 1;
  if (dirDown) {
      extra = 0;
  }
  return [...Array(end - start).keys()].map(v => start + v + extra);
}
function temporarilyDisable() {
    radios.forEach((item) => {
      item.setAttribute('disabled', true);
      setTimeout(() => { 
        item.removeAttribute('disabled');
      }, timeout * 1000);
    });
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console