Skip to content

Instantly share code, notes, and snippets.

@KDCinfo KDCinfo/README.md
Last active Aug 2, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.