<html>
<head>
<style>
html {
font-size: 16px;
box-sizing: border-box;
margin: 0;
padding: 0;
}
::before,
::after {
box-sizing: inherit;
}
body {
font-size: 1rem;
}
.container {
max-width: 500px;
margin: 2rem auto;
border: 1px solid #ccc;
padding: 1rem;
}
.input-group {
position: relative;
margin-bottom: 1rem;
padding: 1rem 0;
display: flex;
justify-content: space-around;
align-items: center;
}
.form-control {
padding: .3rem;
flex: 1;
}
.label {
margin-right: 1rem;
}
.button {
width: 100%;
padding: .5rem;
border: none;
background-color: #121212;
color: #fff;
transition: all .3s;
cursor: pointer;
}
.button:hover {
background-color: #232323;
}
.tooltip {
display: none;
position: absolute;
top: 15px;
right: -150;
min-width: 125px;
max-width: 250px;
background-color: #cb2431;
color: #fff;
padding: .5rem;
font-size: .8rem;
word-wrap: break-word;
}
.tooltip::before {
content: '';
position: absolute;
left: -12px;
top: 10px;
width: 0;
height: 0;
background-color: transparent;
border: 6px solid transparent;
border-right-color: #cb2431;
}
.tooltip.show {
display: block;
}
@media screen and (max-width: 960px) {
.tooltip {
right: 0;
top: -40px;
}
}
</style>
</head>
<body>
<div class="container">
<form id="form" action="#" method="post">
<div class="input-group">
<label for="name" class="label">Name: </label>
<input type="text" name="name" id="name" class="form-control">
<span class="tooltip"> Campo Requerido </span>
</div>
<div class="input-group">
<input type="submit" class="button">
</div>
</form>
</div>
<script>
(function() {
const form = document.getElementById('form');
const inputs = Array.from(form.querySelectorAll('input:not([type="submit"])'));
function _hideTooltips() {
const tooltips = Array.from(form.querySelectorAll('.tooltip'));
tooltips.forEach((e) => {
e.innerHTML = '';
e.classList.remove('show');
});
};
form.addEventListener('submit', function(e) {
e.preventDefault();
_hideTooltips();
// campos requeridos
inputs.forEach((e) => {
if (e.value === '') {
// [NOTA]:
// SOLO FUNCIONA SI EL tootip se encuentra despues del
// input en el DOM. De otra forma debera asociarse un ID
// o seleccionarlo aplicando DOM Traversing.
e.nextElementSibling.innerHTML = 'Campo Requerido';
e.nextElementSibling.classList.add('show');
}
});
});
})();
</script>
</bdoy>
</html>