Email domain auto-suggest

by Jorgelig

HTML

<label>
  <div>e-mail</div>
  <input id=input type=email>
  <datalist id=list></datalist>
</label>

CSS

body
{
  max-width: 20em;
  margin: 1em auto;
  font-family: sans-serif;
}

p
{
  color: gray;
}

a
{
  color: inherit;
}

h1
{
  font-size: 1.5em;
}

hr
{
  margin: 2em 0;
  border-width: 1px 0 0 0;
}

label
{
  font-size: 2em;
}

input
{
  width: 100%;
  font-size: 1em;
}

pre
{
  white-space: normal;
}

JavaScript

var domains = [
  'gmail.com',
  'hotmail.com',
  'mail.com',
  'msn.com',
  'aol.com',
  'googlemail.co.uk',
  'facebook.com',
  'yahoo.com',
  'example.com'
];
var input = document.getElementById('input');
var list = document.getElementById('list');

// Does not behave extremely well on IE10
// i.e. - after entering ”example@” shows no options,
//      - “example@g” — options for “[email protected]”
//      - backspacing to ”example@” — all options
//      - backspacing to “example” and further still
//        shows all options
// But <datalist> update properly, so the problem lies
// with IE's updating displayed options.

//document.querySelector('.debug').hidden = false;




document.querySelector('[type=email]').addEventListener('input', function (event) {
  var emailParts = event.target.value.split('@', 2);
  // Can be further improved:
  // - do not recreate <datalist>'s contents,
  //   when there is no need to.
  // - some fuzzy searching
  // - after entering an email, we could suggest
  //   the part before @ as a name (but not
  //   autocomplete as it would increase number
  //   of fake names)
  list.innerHTML = '';
  if (1 < emailParts.length)
  {
    domains.forEach(function (domain) {
      var option;
      var value = emailParts[0] + '@' + domain;
      if (value === event.target.value)
      {
        return;
      }
      else if (value.substr(0, event.target.value.length) === event.target.value)
      {
        option = document.createElement('option');
        option.value = value;
        list.appendChild(option);
      }
    });
    input.setAttribute('list', list.innerHTML ? list.id : null);
  }
  document.querySelector('pre').textContent = list.innerHTML;
});