I’m trying to learn how to display placeholder text in older browsers. I’ve succeeded in applying the following code (taken from p224 of “DOM Scripting”, by Jeremy Keith) to a single input by its ID…
function elementSupportsAttribute(element, attribute) {
if (!document.createElement) return false;
var test = document.createElement(element);
return (attribute in test); }
if (!elementSupportsAttribute('input', 'placeholder')) {
var input = document.getElementById('search')
input.onfocus = function () {
var text = this.placeholder || this.getAttribute('placeholder');
if (this.value == text) {
this.value = ''; }
}
input.onblur = function () {
if (this.value == '') {
this.value = this.placeholder || this.getAttribute('placeholder'); }
}
input.onblur(); }
I’m struggling with Jeremy Keith’s code for a complete form, which isn’t explained very well. Snippets below from p266 of his book.
function resetFields(whichform) {
if (Modernizr.input.placeholder) return;
//I need to change the above line to use the test function instead
for (var i=0; i<whichform.elements.length; i++) {
var element = whichform.elements[i];
if (element.type == "submit") continue;
if (!element.getAttribute('placeholder')) continue;
element.onfocus = function() {
if (this.value == this.getAttribute('placeholder')) {
this.value = ""; }
}
element.onblur = function() {
if (this.value == "") {
this.value = this.getAttribute('placeholder'); }
}
element.onblur(); }
}
function prepareForms() {
for (var i=0; i<document.forms.length; i++) {
var thisform = document.forms[i];
resetFields(thisform); }
}
Can anyone explain exactly how these functions should be used and how I can change “resetFields” to use the test function from the first code example, instead of Modernizer?