Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- 
This is a remix of 'Swappy radios':
https://codepen.io/liamj/pen/NegxNB
Like the other pen, animations are added with JS, so that this still works (without animation) without JS.
-->
<div class="swappy-radios" role="radiogroup" aria-labelledby="swappy-radios-label">
  <h3 id="swappy-radios-label">Select an option</h3>
  <div class="radio-wrapper">
    <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>
</div>


              
            
!

CSS

              
                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;
}
.radio-wrapper {
  position: relative;
  overflow: hidden;
}
.swappy-radios {
  label {
    -webkit-tap-highlight-color: rgba(0,0,0,0);
    display: block;
    position: relative;
    padding-left: 4rem;
    cursor: pointer;
    font-size: 2rem;
    user-select: none;
    color: #555;
    margin-bottom: .5rem; //prevent clipping of bottom element
    &:hover input ~ .radio {
      //using opacity for hover effect, because background is used (amd delayed!) for the shuffle
      opacity: 0.8;
    }
    &:not(:last-of-type) {
      margin-bottom: 1.5rem;
    }
  }
  
  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.5s;
        }
      }
    }
  }
  .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.5s;
    }
  }
}

              
            
!

JS

              
                let currentValue = 1;
const timeout = 0.5;
const radios = document.querySelectorAll('.swappy-radios input');
const fakeRadios = document.querySelectorAll('.swappy-radios .radio');
const extrasWrapper = document.querySelector('.radio-wrapper');
const countFakesToAppend = fakeRadios.length - 1;

//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

//Append the extra (off-screen) radios, above and below the initially visible ones.
let topExtrasDistance = indicitiveDistance;
//Get position of last initiually visible radio, to offset the trailing extras
const lastRadio = extrasWrapper.lastElementChild.querySelector('.radio');
const parentY = extrasWrapper.getBoundingClientRect().y;
const lastRadioY = lastRadio.getBoundingClientRect().y;
const lastRadioPos = lastRadioY - parentY;
let bottomExtrasDistance = indicitiveDistance;
[...Array(countFakesToAppend)].map(() => {  
  extraTopRadio = document.createElement('span');
  extraTopRadio.classList.add('radio', 'not-real');
  const extraBottomRadio = extraTopRadio.cloneNode();
  extraTopRadio.style.cssText = `top: -${topExtrasDistance}px`;
  extraBottomRadio.style.cssText = `top: ${lastRadioPos + bottomExtrasDistance}px`;
  extrasWrapper.appendChild(extraBottomRadio);
  extrasWrapper.insertBefore(extraTopRadio, extrasWrapper.firstChild);
  topExtrasDistance = topExtrasDistance + indicitiveDistance;
  bottomExtrasDistance = bottomExtrasDistance + indicitiveDistance;
});

//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;
    
    const css = `
      .radio { 
        animation: move ${timeout}s; 
      }
      @keyframes move {
        0% { transform: translateY(0); }
        100% { transform: translateY(${dirDown ? '-' : ''}${yDiff}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 temporarilyDisable() {
  radios.forEach((item) => {
    item.setAttribute('disabled', true);
    setTimeout(() => { 
      item.removeAttribute('disabled');
    }, timeout * 1000);
  });
}
              
            
!
999px

Console