Placeholder attributes

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?

To get around the modernizr test, you could take the test you use for placeholder:

if (Modernizr.input.placeholder) return;
if (elementSupportsAttribute('input', 'placeholder')) return;

// of course since we use this call twice now, it feels a bit manual 
// and each time it requires an element to be created
// you could cache it:
var isPlaceholderSupported = elementSupportsAttribute('input', 'placeholder');

If you would invoke all of your code after page load (or better yet, why not place your JS at the bottom of the page), it should all work I think.

It might also be worth taking a look at some other Placeholder Polyfill scripts to see what others have done :slight_smile:

or if jQuery plugins are more your cup of tea:

No, I can’t get it to work.

That script to which you linked wouldn’t be much use, because I want to include a textarea and an input type of “email”.

Thanks for your help anyway.