How to set blank default text on input field and clear it when element is active.
In modern browsers, you may set the placeholder
attribute on a field to set its default text.
<input type="text" placeholder="Type some text" id="myField" />
However, in older browsers, you may use JavaScript to capture the focus and blur events:
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling if (elem.addEventListener) elem.addEventListener(type, fn, false); else if (elem.attachEvent) elem.attachEvent('on' + type, fn); }, textField = document.getElementById('myField'), placeholder = 'Type some text'; // The placeholder text addEvent(textField, 'focus', function() { if (this.value === placeholder) this.value = ''; }); addEvent(textField, 'blur', function() { if (this.value === '') this.value = placeholder; });
Demo: http://jsbin.com/utecu
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With