Skip to content

Instantly share code, notes, and snippets.

@kauhat
Created August 22, 2017 09:38
Show Gist options
  • Save kauhat/4af7dddf3ef04062c6b65a0be7dae3f7 to your computer and use it in GitHub Desktop.
Save kauhat/4af7dddf3ef04062c6b65a0be7dae3f7 to your computer and use it in GitHub Desktop.
Progressively enhance email inputs using mailcheck.js
/**
* Dynamically add mailcheck to specified input fields on page load.
* To use this, add the `mailcheck` class to your input elements.
* Optionally use a `data-mc-hint-class` attribute to customize the class used for the hints.
* See https://github.com/mailcheck/mailcheck for more
*/
import mailcheck from 'mailcheck'
import _ from 'lodash'
const defaultHintClass = 'help-block'
// Run set-up on page load
document.addEventListener('DOMContentLoaded', () => {
let mailcheckInputs = document.getElementsByClassName('mailcheck')
for (let mailcheckInput of mailcheckInputs) {
let hintElement = document.createElement('span')
// Add classes to hint element
hintElement.classList.add(mailcheckInput.dataset.mcHintClass || defaultHintClass)
// Insert hint element after input fields
mailcheckInput.parentNode.insertBefore(hintElement, mailcheckInput.nextSibling)
// Get display on user input
mailcheckInput.addEventListener('keyup', _.debounce((event) => {
// Get suggestions
mailcheck.run({
email: event.target.value,
suggested: (suggestion) => {
// Create link element for our suggestion
let suggestionLink = document.createElement('a')
suggestionLink.href = 'javascript:void(0)'
suggestionLink.innerText = suggestion.full
// Make suggestion link clickable
suggestionLink.addEventListener('click', () => {
event.target.value = suggestion.full
return false
})
// Build suggestion inside a temporary DOM fragment
let fragment = document.createDocumentFragment()
fragment.appendChild(document.createTextNode('Did you mean '))
fragment.appendChild(suggestionLink)
fragment.appendChild(document.createTextNode('?'))
// Clear existing suggestions and apply
hintElement.innerHTML = ''
hintElement.appendChild(fragment)
},
empty: (element) => {
hintElement.innerHTML = ''
}
})
}, 200))
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment