suburban glory

A Blog in Suburban Glory:
Web Dev Ideas and Inspiration

Using JavaScript to emulate HTML5 placeholders in Internet Explorer

|| Category: JavaScript ||

HTML5 is now the default choice of HTML version for most developers but poor support in Internet Explorer has proven to be a hindrance to the wider adoption of the language.

This lack of native support in IE has lead to a wide array of workarounds which now come under the banner of polyfills. These usually consist of a JavaScript solution that replaces the lack of advanced HTML support in legacy browsers.

A comprehensive polyfill list curated by Paul Irish can be found on GitHub.

alternative HTML5 logoImage reproduced with kind permission from Phil Banks.Twitter: https://twitter.com/#!/emirpprime; Website: http://stickmanphotography.co.uk/

But where possible it is always best to create your own solution rather than rely on somebody else's script.

Placeholders are a new HTML5 attribute which allow text to be placed in a form input field so as to guide the user to what they should be entering. They are a great asset to usability in form design.

Form placeholders are integrated in the latest version of Safari, Firefox, Opera and Chrome but are absent from versions of Internet Explorer 9 and below.

Using a little DOM JavaScript and the for loop it is possible to emulate their behaviour in IE.

This tutorial will run through the following steps:

1. Use Modernizr object detection to check whether the browser is capable of using HTML5 placeholders.

2. If not, loop through form elements replacing the blank input value with that of the placeholder attribute value.

3. Make sure placeholder text in Internet Explorer is a light colour.

4. Make sure placeholder text disappears when user enters value into the input form.

5. Text entered into the input field must have high contrast with the background.

Firstly, if you have not come across Modernizr before then let me introduce you to this essential third party script.

This little helper is an intelligent way of detecting whether various components of HTML5 and CSS3 are present in the user's browser. In this tutorial we will use its object sniffing method like so:


if (!Modernizr.input.placeholder) {

// code here

}

If placeholder is not an active feature of this browser then run some code. First we'll take all the elements for the form with an id of “contact-form” and declare them in a variable called $form.


if (!Modernizr.input.placeholder) {

    var $form;

    $form = document.getElementById('contact-form').elements;

}

Now we'll use a common method to loop through all the form elements and which allows us to give the placeholder value to the form input value. If you are unsure about this method then read Chris Pietschamnn's tutorial.


if (!Modernizr.input.placeholder) {

    var $form, $i;

    $form = document.getElementById('contact-form').elements;

    $i = 0;

    //set placeholder values for internet explorer
    for ($len = $form.length; $i < $len; $i += 1) {

        if ($form[$i].getAttribute(“placeholder”) != undefined) {

            // five placeholder value to form value
            $form[$i].value = $form[$i].getAttribute(“placeholder”);

        } // if not undefined
    } // end for loop

}

And that is it. If you have used the HTML5 placeholder attribute in your form, the text will now be visible in Internet Explorer.

However, we also need to make sure that the placeholder text itself is a light colour. If you need to change the placeholder text in Firefox or Chrome then you can use the follow CSS:


::-webkit-input-placeholder {
   color: #cccccc;
}

:-moz-placeholder {
    color: #cccccc;
}

In JavaScript we'll need to do it by looping through the form input values. Notice the !== submit. We are not interesting in styling the submit input field here, just the input fields such as text and email.


$inputField = document.forms.contactUs.getElementsByTagName('input');

$x = 0;

// loop through input areas to make sure placeholder disappears on focus
for ($len = $inputField.length; $x < $len; $x += 1) {

    if ($inputField[$x].type !== "submit") {

        $inputField[$x].style.color = "#999";


    }

Lastly, we need to make sure that the placeholder text disappears when the user starts to enter their own text and the colour changes to something more darker and readable:


   $inputField = document.forms.contactUs.getElementsByTagName('input');

$x = 0;

// loop through input areas to make sure placeholder disappears on focus
for ($len = $inputField.length; $x < $len; $x += 1) {

    if ($inputField[$x].type !== "submit") {

        $inputField[$x].style.color = "#999";

        // place holder text disappears on focus
        $inputField[$x].onfocus = function () {

            this.value = "";
            this.style.color = "#000";

        };

    }

And altogether the code looks like this:

if (!Modernizr.input.placeholder) {

    // always declare javascript variables at the top of the script
    var $elements, $i, $x, $len, $formInput, $inputField, $form;

    $form = document.getElementById('contact-us').elements;

    $i = 0;

    //set placeholder values for internet explorer
    for ($len = $form.length; $i < $len; $i += 1) {

        if ($form[$i].getAttribute("placeholder") != undefined) {

            $form[$i].value = $form[$i].getAttribute("placeholder");

        } // if not undefined
    } // end for loop

    $inputField = document.forms.contactUs.getElementsByTagName('input');

    $x = 0;

    // loop through input areas to make sure placeholder disappears on focus
    for ($len = $inputField.length; $x < $len; $x += 1) {

        // Don't change the submit input!
        if ($inputField[$x].type !== "submit") {

            // Give placeholder text a grey colour
            $inputField[$x].style.color = "#999";

            //Delete the placeholder text and change CSS text colour to black on user focus
            $inputField[$x].onfocus = function () {

                this.value = "";
                this.style.color = "#000";

            };

        }

    } // if not undefined
} // end modernizr

You can see a live example of this code on a website I built here - will writer - and you grab the code on Gist.

This code has been tested on IE versions 7, 8 and 9.

Comments

Jacob || Sun 6th Nov 2011

This works great! I added this to an external script as a function that I pass the form ID to whenever I need to use it. I also added a function at the end that swaps back in the placeholder and CSS style if the user focuses out with value == 0:

//If user focuses out with nothing typed, revert back to placeholder
	$inputField[$x].onfocusout = function () {
		if (this.value == "") {
			this.value = this.getAttribute("placeholder");
			this.style.color = "#999";
		}
	}

Shaun Mclain || Sun 8th Jan 2012

Nice informative blog, thanks for sharing.

Naxs || Sun 19th Aug 2012

Good point. The max and min attributes are new, but you are corecrt in saying that max length already existed. I have updated the post accordingly.

You can add comments below.
Auto-paragraphing is enabled. Double newlines will be converted to paragraphs.

Allowed tags: a, abbr, acronym, b, blockquote, caption, cite, code, dd, del, dfn, div, dl, dt, em, i, ins, kbd, li, ol, p, pre, s, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var.

If you wish add code examples then please do so between the following tags:

<pre><![CDATA[
Place code here
]]></pre>







mainland