Skip to content

Instantly share code, notes, and snippets.

@KDCinfo
Last active August 2, 2019 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KDCinfo/b31e0b7a204f245cc4d8b163c317d8e4 to your computer and use it in GitHub Desktop.
Save KDCinfo/b31e0b7a204f245cc4d8b163c317d8e4 to your computer and use it in GitHub Desktop.
Simple Automated Tooltips for Form Input Fields

Automated Tooltips for Form Input Fields

Tooltip auto-generated content is based on input placeholder content.

Source HTML

<input type='text' placeholder='Welcome home, World!'>

Expected/Generated HTML

<span class='tooltip-out'>
    <span class='tooltip hidden'>Welcome home, World!</span>
    <input type='text' placeholder='Welcome home, World!'>
</span>
.tooltip-out {
position: relative;
}
.tooltip {
background-color: rgba(255, 255, 200, 0.85);
border: 1px solid darkgreen;
border-radius: 5px;
padding: 1px 5px;
position: absolute;
left: 0;
top: -14px;
z-index: 30;
white-space: nowrap;
}
.hidden {
display: none;
}
const allInputs = document.querySelectorAll("input[type='text'], input[type='password'], input[type='email']");
Array.from(allInputs).forEach(elemInput => {
const spanOut = document.createElement('span'),
spanIn = document.createElement('span');
spanOut.classList.add('tooltip-out');
spanIn.classList.add('tooltip', 'hidden');
spanIn.innerText = elemInput.placeholder;
elemInput.parentNode.insertBefore(spanOut, elemInput);
spanOut.appendChild(spanIn);
spanOut.appendChild(elemInput); // Apparently this 'moves' the element (no need to detach or removeChild).
elemInput.addEventListener('focus', e => {
spanIn.classList.remove('hidden');
});
elemInput.addEventListener('blur', e => {
spanIn.classList.add('hidden');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment