I want to implement a form that displays tooltips whenever a user clicks or focuses on an input field, and the tooltip should disappear when the user clicks elsewhere. While I understand the basics of using JavaScript's getElementById
and click event listeners, I'm unsure of how to toggle the CSS code for tooltips that currently only work on hover. I do not want to use the :active
pseudo-class for this functionality.
HTML:
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In vitae consequat dui, ut ultricies tortor. Fusce imperdiet augue sit amet magna lobortis eleifend. Sed gravida consectetur magna vitae luctus. Suspendisse potenti. Cras luctus porttitor viverra. Aenean ac magna ullamcorper, ullamcorper sem non, mattis felis. Morbi ultricies pretium dui, quis posuere sapien tristique sit amet. Sed et velit tincidunt, convallis enim sed, imperdiet lectus. In quis diam aliquet, pharetra nisi et, interdum eros. Nullam rutrum lectus at est lacinia facilisis. Nullam eu gravida felis. Suspendisse ut magna id nisi fringilla venenatis. Cras facilisis tellus at erat fermentum congue. Nullam dapibus varius nibh, eu pharetra leo vehicula nec.
</p>
<label>Username</label>
<div data-tip="Only A-Z">
<span></span>
<input id='username-input' type="text">
</div>
<label>Password</label>
<div data-tip="8 characters minimum">
<span></span>
<input id='password-input' type="text">
</div>
<label>Email</label>
<div data-tip="E-mail is only for registration">
<span></span>
<input id='email-input' type="text">
</div>
CSS:
[data-tip] {
position: relative;
}
[data-tip]::before {
content: '';
display: none;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-top: 15px solid #ccc;
position: absolute;
top: -10px;
left: 15px;
z-index: 10;
font-size: 1em;
line-height: 2em;
width: 0;
height: 0;
}
[data-tip] > span {
display: none;
border-left: 16px solid transparent;
border-right: 16px solid transparent;
border-top: 16px solid black;
position: absolute;
top: -9px;
left: 14px;
z-index: 7;
font-size: 1em;
line-height: 2em;
width: 0;
height: 0;
}
[data-tip]::after {
display: none;
content: attr(data-tip);
position: absolute;
top: -54px;
left: 0px;
border: 1px solid black;
padding: 10px 20px;
background-color: #ccc;
color: black;
z-index: 9;
font-size: 0.75em;
height: 4em;
text-align: center;
vertical-align: middle;
line-height: 2em;
-webkit-border-radius: 0.5em;
-moz-border-radius: 0.5em;
border-radius: 0.5em;
box-sizing: border-box;
white-space: nowrap;
word-wrap: normal;
}
[data-tip]:hover > span,
[data-tip]:hover::before,
[data-tip]:hover::after {
display: block;
}
JavaScript:
input = document.getElementById('email-input');
input.addEventListener('click', function() {
/* Need help toggling CSS code here */
});