Back
Learn how to create visually appealing and user-friendly floating placeholder input fields that improve readability and UX.
<div class="input-container"> <input type="text" class="floating-input" placeholder=" "> <label class="floating-label">Enter Text Here</label> </div>
document.addEventListener('DOMContentLoaded', function() { const inputs = document.querySelectorAll('.floating-input'); inputs.forEach(input => { input.addEventListener('focus', handleFocus); input.addEventListener('blur', handleBlur); }); function handleFocus(event) { const label = event.target.previousElementSibling; if (label) { label.classList.add('active'); } } function handleBlur(event) { const label = event.target.previousElementSibling; if (label && event.target.value === '') { label.classList.remove('active'); } } });
.input-container { position: relative; margin: 20px 0; } .floating-input { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; background-color: transparent; outline: none; transition: border 0.3s ease; } .floating-input:focus { border-color: #007BFF; } .floating-label { position: absolute; pointer-events: none; left: 15px; top: 10px; transition: 0.3s ease; color: #999; } .floating-input:focus ~ .floating-label, .floating-input:not(:placeholder-shown) ~ .floating-label { top: -15px; left: 10px; font-size: 12px; color: #007BFF; }
<div class="input-container"> <input type="text" class="floating-input" placeholder=" "> <label class="floating-label">Enter Text Here</label> </div> <script> document.addEventListener('DOMContentLoaded', function() { const inputs = document.querySelectorAll('.floating-input'); inputs.forEach(input => { input.addEventListener('focus', handleFocus); input.addEventListener('blur', handleBlur); }); function handleFocus(event) { const label = event.target.previousElementSibling; if (label) { label.classList.add('active'); } } function handleBlur(event) { const label = event.target.previousElementSibling; if (label && event.target.value === '') { label.classList.remove('active'); } } }); </script> <style> .input-container { position: relative; margin: 20px 0; } .floating-input { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; background-color: transparent; outline: none; transition: border 0.3s ease; } .floating-input:focus { border-color: #007BFF; } .floating-label { position: absolute; pointer-events: none; left: 15px; top: 10px; transition: 0.3s ease; color: #999; } .floating-input:focus ~ .floating-label, .floating-input:not(:placeholder-shown) ~ .floating-label { top: -15px; left: 10px; font-size: 12px; color: #007BFF; } .active { top: -15px; left: 10px; font-size: 12px; color: #007BFF; } </style>Thank you for reading this article.
Comments