Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

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

              
                <h1>Making a custom select input</h1>

<div class="sample">
  <label for="custom-select-input">User Type</label>
  <div id='custom-select-status' class='hidden-visually' aria-live="polite"></div>
  <div class="custom-select" id="myCustomSelect">
    <input 
           type="text" 
           id="custom-select-input" 
           class="select-css" 
           aria-describedby="custom-select-info">
    <span id="custom-select-info" class="hidden-visually">Arrow down for options or start typing to filter.</span>
    <span class="custom-select-icons">
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" focusable="false" aria-hidden="true" id="icon-circle-down" class="icon" role="img">
        <path d="M16 8c0-4.418-3.582-8-8-8s-8 3.582-8 8 3.582 8 8 8 8-3.582 8-8zM1.5 8c0-3.59 2.91-6.5 6.5-6.5s6.5 2.91 6.5 6.5-2.91 6.5-6.5 6.5-6.5-2.91-6.5-6.5z"></path>
        <path d="M4.957 5.543l-1.414 1.414 4.457 4.457 4.457-4.457-1.414-1.414-3.043 3.043z"></path>
      </svg>
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" focusable="false" aria-hidden="true" id="icon-circle-up" class="icon hidden-all" role="img">
        <path d="M0 8c0 4.418 3.582 8 8 8s8-3.582 8-8-3.582-8-8-8-8 3.582-8 8zM14.5 8c0 3.59-2.91 6.5-6.5 6.5s-6.5-2.91-6.5-6.5 2.91-6.5 6.5-6.5 6.5 2.91 6.5 6.5z"></path>
        <path  d="M11.043 10.457l1.414-1.414-4.457-4.457-4.457 4.457 1.414 1.414 3.043-3.043z"></path>
      </svg>							
    </span>
    <ul class="custom-select-options hidden-all" id="custom-select-list">
      <li><strong>User</strong><br>Logged in Users can read locked content and update their profile.</li>
			<li><strong>Author</strong><br>Authors can create, edit and delete their own posts.</li>
      <li><strong>Editor</strong><br>Editors can create, edit and delete all posts by all authors.</li>
			<li><strong>Manager</strong><br>Managers have the same permissions as Editors, plus they can create, edit and delete categories, pages and manage comments.</li>
			<li><strong>Administrator</strong><br>Administrators have full control over the posts, pages, categories, themes and plugins of the site.</li>
		</ul>
	</div>
</div>

<!--
  <script src="index.js"></script>
 	<script>
		customSelect('#myCustomSelect', {statusSelector: '#custom-select-status'});
	</script>
-->
              
            
!

CSS

              
                body {
	font-family: sans-serif;
	background: #eeeeee;
}
.wrapper {
	margin: 1em auto;
	text-align: left;
}
.sample {
	border: 1px solid #eeeeee;
	background: #ffffff;
	max-width: 30em;
	padding: 1em;
	margin-bottom: 1em;
}
.custom-select {
	position: relative;
}
.select-css {
	display: block;
	font-size: 1em;
	font-family: sans-serif;
	font-weight: 700;
	color: #444;
	line-height: 1.3;
	padding: .6em 1.4em .5em .8em;
	width: 100%;
	max-width: 100%;
	box-sizing: border-box;
	margin: 0;
	border: 1px solid #aaa;
	box-shadow: 0 1px 0 1px rgba(0,0,0,.04);
	border-radius: .25em;
	-moz-appearance: none;
	-webkit-appearance: none;
	appearance: none;
	background-color: #fff;
	position: relative;
	z-index: 10;
}
.select-css::-ms-expand {
	display: none;
}
.select-css:hover {
	border-color: #888;
}
.select-css:focus {
	border: 2px dashed blue; 
	color: #222;
	outline: none;
}
.custom-select-icons {
	position: absolute;
	top: 0.5em;
	right: 0.5em;
	z-index: 20;
	border: 1px solid white;
	background: transparent;
}
.custom-select-options {
	border: 1px solid #aaa;
	border-radius: 0 0 0.25em .25em;
	line-height: 1.5;
	margin: 0;
	margin-top: -0.5em;
	padding: 0;
	list-style-type: none;
	font-weight:normal;
	cursor: pointer;
	z-index: 2;
	position: absolute;
	width: calc(100% - 1px);
	background-color: #ffffff;
}
.custom-select-options li {
	padding: 1em;
}
.custom-select-options li:hover {
	background: blue;
	color: #fff;
	border: 1px solid blue;
	border-width: 0 0 0 1px;
}

.custom-select-options li:focus {
	border: 2px dashed blue;
}
.icon {
		fill: ButtonText;
		pointer-events: none;
	}
@media screen and (-ms-high-contrast: active) {
	.icon {
		fill: ButtonText;
	}
}
.hidden-all {
	display: none;
}
.hidden-visually {
	position: absolute;
	width: 1px;
	height: 1px;
	padding: 0;
	overflow: hidden;
	clip: rect(0,0,0,0);
	white-space: nowrap;
	-webkit-clip-path: inset(50%);
	clip-path: inset(50%);
	border: 0;}

              
            
!

JS

              
                const customSelect = function (element, overrides) {

  // SETUP
  // /////////////////////////////////
  // assign names to things we'll need to use more than once

  const defaults = {
    inputSelector: 'input',
    listSelector: 'ul',
    optionSelector: 'li',
    statusSelector: '[aria-live="polite"]'
  };

  const options = Object.assign({},
    defaults, 
    overrides
  );

  const csSelector = document.querySelector(element) // the input, svg and ul as a group
  const csInput = csSelector.querySelector(options.inputSelector)
  const csList = csSelector.querySelector(options.listSelector)
  const csOptions = csList.querySelectorAll(options.optionSelector)
  // const csIcons = csSelector.querySelectorAll('svg')
  const csStatus = document.querySelector(options.statusSelector)
  const aOptions = Array.from(csOptions)

  // when JS is loaded, set up our starting point
  // if JS fails to load, the custom select remains a plain text input
  // create and set start point for the state tracker
  let csState = "initial"
  // inform assistive tech (screen readers) of the names & roles of the elements in our group
  csSelector.setAttribute('role', 'combobox') 
  csSelector.setAttribute('aria-haspopup', 'listbox') 
  csSelector.setAttribute('aria-owns', 'custom-select-list') // container owns the list...
  csInput.setAttribute('aria-autocomplete', 'both') 
  csInput.setAttribute('aria-controls', 'custom-select-list') // ...but the input controls it
  csList.setAttribute('role', 'listbox') 
  csOptions.forEach(function(option) {
    option.setAttribute('role', 'option') 
    option.setAttribute('tabindex', "-1")  // make li elements keyboard focusable by script only
  })


  // EVENTS
  // /////////////////////////////////
  csSelector.addEventListener('click', function(e) {
    const currentFocus = findFocus()
    switch(csState) {
      case 'initial' : // if state = initial, toggleOpen and set state to opened
        toggleList('Open')
        setState('opened')
        break
      case 'opened':
        // if state = opened and focus on input, toggleShut and set state to initial
        if (currentFocus === csInput) {
          toggleList('Shut')
          setState('initial')
        } else if (currentFocus.tagName === 'LI') {
          // if state = opened and focus on list, makeChoice, toggleShut and set state to closed
          makeChoice(currentFocus)
          toggleList('Shut')
          setState('closed')
        }
        break
      case 'filtered':
        // if state = filtered and focus on list, makeChoice and set state to closed
        if (currentFocus.tagName === 'LI') {
          makeChoice(currentFocus)
          toggleList('Shut')
          setState('closed')
        } // if state = filtered and focus on input, do nothing (wait for next user input)

        break
      case 'closed': // if state = closed, toggleOpen and set state to filtered? or opened?
        toggleList('Open')
        setState('filtered')
        break
    }
  })

  csSelector.addEventListener('keyup', function(e) {
    doKeyAction(e.key)
  })

  document.addEventListener('click', function(e) {
    if (!e.target.closest('#myCustomSelect')) {
      // click outside of the custom group
      toggleList('Shut')
      setState('initial')
    } 
  })

  // FUNCTIONS 
  // /////////////////////////////////

  function toggleList(whichWay) {
    if (whichWay === 'Open') {
      csList.classList.remove('hidden-all')
      csSelector.setAttribute('aria-expanded', 'true')
    } else { // === 'Shut'
      csList.classList.add('hidden-all')
      csSelector.setAttribute('aria-expanded', 'false')
    }
  }

  function findFocus() {
    const focusPoint = document.activeElement
    return focusPoint
  }

  function moveFocus(fromHere, toThere) {
    // grab the currently showing options, which might have been filtered
    const aCurrentOptions = aOptions.filter(function(option) {
      if (option.style.display === '') {
        return true
      }
    })
    // don't move if all options have been filtered out
    if (aCurrentOptions.length === 0) {
      return
    }
    if (toThere === 'input') {
      csInput.focus()
    }
    // possible start points
    switch(fromHere) {
      case csInput:
        if (toThere === 'forward') {
          aCurrentOptions[0].focus()
        } else if (toThere === 'back') {
          aCurrentOptions[aCurrentOptions.length - 1].focus()
        }
        break
      case csOptions[0]: 
        if (toThere === 'forward') {
          aCurrentOptions[1].focus()
        } else if (toThere === 'back') {
          csInput.focus()
        }
        break
      case csOptions[csOptions.length - 1]:
        if (toThere === 'forward') {
          aCurrentOptions[0].focus()
        } else if (toThere === 'back') {
          aCurrentOptions[aCurrentOptions.length - 2].focus()
        }
        break
      default: // middle list or filtered items 
        const currentItem = findFocus()
        const whichOne = aCurrentOptions.indexOf(currentItem)
        if (toThere === 'forward') {
          const nextOne = aCurrentOptions[whichOne + 1]
          nextOne.focus()
        } else if (toThere === 'back' && whichOne > 0) {
          const previousOne = aCurrentOptions[whichOne - 1]
          previousOne.focus()
        } else { // if whichOne = 0
          csInput.focus()
        }
        break
    }
  }

  function doFilter() {
    const terms = csInput.value
    const aFilteredOptions = aOptions.filter(function(option) {
      if (option.innerText.toUpperCase().startsWith(terms.toUpperCase())) {
        return true
      }
    })
    csOptions.forEach(option => option.style.display = "none")
    aFilteredOptions.forEach(function(option) {
      option.style.display = ""
    })
    setState('filtered')
    updateStatus(aFilteredOptions.length)
  }

  function updateStatus(howMany) {
    csStatus.textContent = howMany + " options available."
  }

  function makeChoice(whichOption) {
    const optionTitle = whichOption.querySelector('strong')
    csInput.value = optionTitle.textContent
    //csInput.setAttribute('value', optionTitle.textContent)
    moveFocus(document.activeElement, 'input')
    // update aria-selected, if using
  }

  function setState(newState) {
    switch (newState) {
      case 'initial': 
        csState = 'initial'
        break
      case 'opened': 
        csState = 'opened'
        break
      case 'filtered':
        csState = 'filtered'
        break
      case 'closed': 
        csState = 'closed'
    }
    // console.log({csState})
  }

  function doKeyAction(whichKey) {
    const currentFocus = findFocus()
    switch(whichKey) {
      case 'Enter':
        if (csState === 'initial') { 
          // if state = initial, toggleOpen and set state to opened
          toggleList('Open')
          setState('opened')
        } else if (csState === 'opened' && currentFocus.tagName === 'LI') { 
          // if state = opened and focus on list, makeChoice and set state to closed
          makeChoice(currentFocus)
          toggleList('Shut')
          setState('closed')
        } else if (csState === 'opened' && currentFocus === csInput) {
          // if state = opened and focus on input, close it
          toggleList('Shut')
          setState('closed')
        } else if (csState === 'filtered' && currentFocus.tagName === 'LI') {
          // if state = filtered and focus on list, makeChoice and set state to closed
          makeChoice(currentFocus)
          toggleList('Shut')
          setState('closed')
        } else if (csState === 'filtered' && currentFocus === csInput) {
          // if state = filtered and focus on input, set state to opened
          toggleList('Open')
          setState('opened')
        } else { // i.e. csState is closed, or csState is opened/filtered but other focus point?
          // if state = closed, set state to filtered? i.e. open but keep existing input? 
          toggleList('Open')
          setState('filtered')
        }
        break

      case 'Escape':
        // if state = initial, do nothing
        // if state = opened or filtered, set state to initial
        // if state = closed, do nothing
        if (csState === 'opened' || csState === 'filtered') {
          toggleList('Shut')
          setState('initial')
        }
        break

      case 'ArrowDown':
        if (csState === 'initial' || csState === 'closed') {
          // if state = initial or closed, set state to opened and moveFocus to first
          toggleList('Open')
          moveFocus(csInput, 'forward')
          setState('opened')
        } else {
          // if state = opened and focus on input, moveFocus to first
          // if state = opened and focus on list, moveFocus to next/first
          // if state = filtered and focus on input, moveFocus to first
          // if state = filtered and focus on list, moveFocus to next/first
          toggleList('Open')
          moveFocus(currentFocus, 'forward')
        } 
        break
      case 'ArrowUp':
        if (csState === 'initial' || csState === 'closed') {
          // if state = initial, set state to opened and moveFocus to last
          // if state = closed, set state to opened and moveFocus to last
          toggleList('Open')
          moveFocus(csInput, 'back')
          setState('opened')
        } else {
          // if state = opened and focus on input, moveFocus to last
          // if state = opened and focus on list, moveFocus to prev/last
          // if state = filtered and focus on input, moveFocus to last
          // if state = filtered and focus on list, moveFocus to prev/last
          moveFocus(currentFocus, 'back')
        }
        break 
      default:
        if (csState === 'initial') {
          // if state = initial, toggle open, doFilter and set state to filtered
          toggleList('Open')
          doFilter()
          setState('filtered')
        } else if (csState === 'opened') {
          // if state = opened, doFilter and set state to filtered
          doFilter()
          setState('filtered')
        } else if (csState === 'closed') {
          // if state = closed, doFilter and set state to filtered
          doFilter()
          setState('filtered')
        } else { // already filtered
          doFilter()
        }
        break 
    }
  }

};

customSelect('#myCustomSelect', {statusSelector: '#custom-select-status'});
              
            
!
999px

Console