Toggle navigation
☰
Home
HTML
CSS
Scripting
Database
<!DOCTYPE html> <title>My Example</title> <style> .char-counter-container { max-width: 500px; margin: 40px auto; font-family: sans-serif; padding: 30px; background: #f8f9fa; border-radius: 8px; } .char-counter-container h3 { text-align: center; margin-top: 0; } .form-group { position: relative; } .form-group label { display: block; font-weight: 500; margin-bottom: 5px; } .form-group textarea { width: 100%; height: 120px; padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-size: 1rem; box-sizing: border-box; resize: vertical; } .form-group textarea:focus { outline: none; border-color: #007bff; } /* -- Counter styles -- */ .char-counter { text-align: right; font-size: 0.9rem; color: #6c757d; margin-top: 5px; transition: color 0.2s; } /* Optional: change color when nearing/at the limit */ .char-counter.warning { color: #ffc107; font-weight: 500; } .char-counter.error { color: #dc3545; font-weight: bold; } </style> <div class="char-counter-container"> <h3>Compose a Short Bio</h3> <form action="#" method="post"> <div class="form-group"> <label for="bio-textarea">Your Bio</label> <textarea id="bio-textarea" name="bio" maxlength="140" placeholder="Tell us something about yourself..."></textarea> <!-- The character counter will be updated by JavaScript --> <div class="char-counter" id="char-counter">0/140</div> </div> <button type="submit">Save</button> </form> </div> <script> const textArea = document.getElementById('bio-textarea'); const charCounter = document.getElementById('char-counter'); if (textArea && charCounter) { const maxLength = textArea.getAttribute('maxlength'); textArea.addEventListener('input', () => { const currentLength = textArea.value.length; // Update the text charCounter.textContent = `${currentLength}/${maxLength}`; // Update the color based on length // e.g., show warning at 90% of the max length if (currentLength >= maxLength) { charCounter.className = 'char-counter error'; } else if (currentLength >= maxLength * 0.9) { charCounter.className = 'char-counter warning'; } else { charCounter.className = 'char-counter'; } }); } </script>