Skip to content

Instantly share code, notes, and snippets.

@adamschwartz
Last active March 26, 2021 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamschwartz/bc81016d0068ffed4c00e8fce805b982 to your computer and use it in GitHub Desktop.
Save adamschwartz/bc81016d0068ffed4c00e8fce805b982 to your computer and use it in GitHub Desktop.
<form>
<div prefix-editor suffix=".adamschwartz.com" spellcheck="false" autocomplete="false">
<input type="text">
</div>
</form>
<script>
(() => {
const editorEl = document.querySelector('[prefix-editor]')
const inputEl = editorEl.querySelector('input')
const suffix = editorEl.getAttribute('suffix')
const mimicEl = document.createElement('div')
mimicEl.appendChild(document.createElement('span'))
mimicEl.appendChild(document.createElement('span'))
mimicEl.querySelector('span:last-child').textContent = suffix
inputEl.addEventListener('keydown', (event) => {
if (!event.key || !event.key.match(/[A-Z0-9\-]/i)) {
event.preventDefault()
}
})
const changeEvents = ['input', 'change']
changeEvents.forEach((name) => {
inputEl.addEventListener(name, (event) => {
mimicEl.querySelector('span:first-child').textContent = inputEl.value
})
})
editorEl.appendChild(mimicEl)
})()
</script>
<style>
* {
box-sizing: border-box;
}
form {
display: block;
font-size: 16px;
font-family: Avenir;
margin: 1em auto;
padding: 1em;
background: #eee;
width: 30em;
max-width: 100%;
}
[prefix-editor] {
position: relative;
width: 100%
}
[prefix-editor] > input, [prefix-editor] > div {
width: 100%;
border: 1px solid #ccc;
font: inherit;
padding: .6em 1em;
line-height: 1.3;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[prefix-editor] > input {
position: absolute
}
[prefix-editor] > input:focus {
outline: none;
border-color: #2f7bbf
}
[prefix-editor] > div {
opacity: .4;
position: relative;
border-color: transparent;
pointer-events: none
}
[prefix-editor] > div > span:first-child {
opacity: 0
}
</style>
@adamschwartz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment