Page 1 of 1

How To Use The Placeholder Attribute of HTML 5 & Create A Fallback Rate Topic: -----

#1 EnvXOwner  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 357
  • View blog
  • Posts: 2,319
  • Joined: 10-August 09

Posted 17 September 2011 - 09:26 AM

Hello there everyone! Today, I'm going to show you how to use the placeholder attribute of form elements in HTML 5, and how to create a fallback with jQuery. Now, let's look at the history and browser support for the placeholder attribute of HTML 5. Now, essentially what the placeholder attribute does is it provides text inside an input field. When you look at the field, there's text in it. When you click on the text box, it disappears. If you leave the text box, and there is no text in there, it'll reappear. That's also what our jQuery fallback will do, more on that later. Placeholder is supported in the following browsers:

IE: None Firefox: 3.7+ Safari: 4+ Chrome: 4+ Opera: 11+ iPhone: 4+ Android: None

With this in mind, we can see that, in my mind, the most troublesome browser IE doesn't support placeholder at all, neither does the Android browser. Thankfully, this can be fixed using jQuery. There are also older versions of modern browsers that don't support it, this jQuery code will work for those browsers also :). Now, let's get the basic structure of our HTML document. All the HTML documents in all my tutorials will be the same (just a hint).

<!DOCTYPE html>

<html>
	<head>
		<meta charset="utf-8" />
	</head>
	
	<body>
	
	</body>
</html>


Now that we have the basic outline done we can begin making our simple form. Also, in this tutorial we won't be doing any styling since it's not needed (actually that's a lie, we'll be doing changing the color of font with some jQuery magic). We're basically done with the HTML layout, but you can add a lot more if you want. Before we can do anything with jQuery, we need to add the script to our head element. I will be using Google's CDN hosted version of the minimized version of jQuery 1..6.2 that can be found here. Here is my code for adding it to the head element.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>


Now, that we have jQuery being linked to our HTML document, let's get the form done, shall we.

<form>
	<input type="text" id="placeholder-fallback" placeholder="Placeholder Tutorial" />
</form>


Now, there isn't much to explain there, we create our form with one input field. It's a text input with the id of “placeholder-fallback”, we will need it for the jQuery. We also set the placeholder attribute and that's about it. You can add other form elements, but this is all that we need for the purpose of this tutorial. Now we're ready to dip our feet into jQuery. You don't have to know to much Javascript for this tutorial, but I do suggest that you understand basic programming. Like setting a variable to something and creating if statements. We're going to embed this into our HTML document, but you may use an external Javascript file. Let's set up our script tags in our head element.

<script type=”text/javascript”>
</script>


Okay, now I'm going to cut up this wall of jQuery so that it's easier to understand. I'll also explain each block. To start we need to add this little bit of jQuery.

$(function() {
})


All of our jQuery will go in that function. Also, just so you guys know when I say jQuery or Javascript in this tutorial, I mean both at the same time. Alright. Now let's create another function to see if the placeholder attribute is being recognized inside the input, if it isn't being recognized then we know it's not supported, if it is recognized then it's supported. Easy isn't it? Well, here's the function.

function placeholder_supported() {
	var input = document.createElement("input");
	     return('placeholder' in input);
}
				
var placeholder_supported = placeholder_supported();


Alright so we create a function with a name that I thought would be pretty obvious. Then we create a variable called input and create an input element. We then return the placeholder attribute inside the input. We then create a variable outside the function that is equal to the function. When ever we use that variable, we're checking whether or not placeholder is supported or not. Okay, we are now going to check if it's false. If placeholder is returned false, it isn't supported, if it's true, then it is supported. If it's true, we're not going to do anything and continue to display the HTML 5 placeholder attribute as it is. If it isn't, well I'll just show you the code.

if (placeholder_supported == false) {
	//	There isn't any HTML5 placeholder support so we're going to set the value to what we want it to be.
	$('#placeholder-fallback').val('Placeholder Tutorial');
	$('#placeholder-fallback').css({'color' : '#C0C0C0'});
}


If the placeholder attribute isn't supported we set a value for the #placeholder-fallback, remember that was the id we set to our input field. You may, if you want, create a function that passes the id of the input, but for simplicity, we will hard code the ids into the functions and if statements. We also set the color of that form element to gray. This will fix the placeholder when you load the page, but what about when you focus on the form or leave the form. It'll stay the same way. Not disappearing or reappearing. To fix that we need to use the focus and blur functions of jQuery. Here's the focus function.


$('#placeholder-fallback').focus(function() {
	if (placeholder_supported == false) {
		if ($(this).val() == 'Placeholder Tutorial') {
			$(this).val('');
			$('#placeholder-fallback').css({'color' : '#000000'});
		}
	}
});


Okay, we're performing the focus function on the #placeholder-fallback form element. We then check if the placeholder attribute isn't supported again and if it isn't we check the value using $(this), basically referencing the element, and see if the value is what we have it equal to. If it is, we clear the value and set the color of the text back to black. Now, when you click on on the form element the text disappears, but if you leave the form element, the placeholder doesn't reappear. Let's fix that with the blur function.

$('#placeholder-fallback').blur(function() {
	if (placeholder_supported == false) {
		if ($(this).val() == '') {
			$(this).val('Placeholder Tutorial');
			$('#placeholder-fallback').css({'color' : '#C0C0C0'});
		}
	}
});


This is basically doing the opposite of what we did when using the focus function. We use the blur function of jQuery on the #placeholder-fallback form element. We then check if the placeholder attribute isn't supported again and if it isn't we check the value using $(this). If it is empty, we set the value to what we have the placeholder set to and change the color back to gray. Now, the form should work like it does when using the HTML 5 placeholder attribute.

Yay! We did it guys! We outsmarted older browsers. I hope this tutorial taught you how to use the placeholder attribute and how to create a fallback with jQuery. I'm sure that there are other ways to accomplish this and ways to optimize it. If you guys got any suggestions or questions, leave a comment below. Thanks for reading!

As always here is a zip of the tutorial :)
Attached File  placeholder tutorial.zip (854bytes)
Number of downloads: 483

This post has been edited by EnvXOwner: 17 September 2011 - 04:23 PM


Is This A Good Question/Topic? 1
  • +

Replies To: How To Use The Placeholder Attribute of HTML 5 & Create A Fallback

#2 EnvXOwner  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 357
  • View blog
  • Posts: 2,319
  • Joined: 10-August 09

Posted 17 September 2011 - 07:25 PM

I wanted to let you guys know, the reason I created this tutorial is because just today, I had to make placeholders work in older versions of IE. I only used it once, so I made this tutorial like this. Now I've used it twice. So I made it into a function. Now, I won't be doing a tutorial on how to make my above code into a function (basically I won't explain it, most of it is self explanatory). If you guys want to use this as a function, here is the code to do it :):

placeholder.js (I put it in an external JS file):

function set_placeholder(input, placeholder) {	
		$(function() {
			function placeholder_supported() {
				var input = document.createElement("input");
				return('placeholder' in input);
			}
						
			var placeholder_supported = placeholder_supported();
			
			if (placeholder_supported == false) {
				//	There isn't any HTML5 placeholder support so we're going to set the value to what we want it to be.
				$(input).val(placeholder);
				$(input).css({'color' : '#C0C0C0'});
			}
						
			$(input).focus(function() {
				if (placeholder_supported == false) {
					if ($(this).val() == placeholder) {
						$(this).val('');
						$(input).css({'color' : '#000000'});
					}
				}
			});
						
			$(input).blur(function() {
				if (placeholder_supported == false) {
					if ($(this).val() == '') {
						$(this).val(placeholder);
						$(input).css({'color' : '#C0C0C0'});
					}
				}
			});
	})
}


Here's what you would use on the HTML document:

set_placeholder('#placeholder-fallback', 'Placeholder Tutorial');


I hope that you guys like this tutorial. I love feedback :)
Was This Post Helpful? 0
  • +
  • -

#3 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Posted 17 September 2011 - 09:21 PM

Hey.

I didn't know there was an actual HTML5 element that did that. I'm so used to using the Javascript route I didn't even consider it. Thanks for pointing it out! :D

There are a few things in your code, though, that could be improved upon.

Firstly, you use the jQuery ready event ($(function()..)) inside of your set_placeholder function, which is odd because it's used to set code to execute as soon as the DOM is ready, which might be after your function is called. A better way would be to not nest your function code inside the ready event but rather make sure the set_placeholder calls aren't made until after the ready event has fired. - If you are planing to call the function in the actual HTML, you really shouldn't; script tags in the body is best avoided. Instead you may want to consider using jQuery to look for placeholder attributes on input elements (the would exist in the DOM if they are set in the HTML, even if the browsers doesn't support the functionality they are meant to provide) and call the function on those elements. Something along the lines of:
$(function() {
    $("input[placeholder]").each(function() {
        set_placeholder($(this), $(this).attr("placeholder"));
    });
});



Also, you are setting the focus and blur functions on the input even in browsers that do support the placeholder element, only checking to see if they should have been called after they have been. It would make more sense to only set the events if the browser has need of it.

And lastly, you are redefining and calling the placeholder_supported function inside every call to set_placeholder which is kind of pointless seeing as it will always return the same result.

To address all of that, I would suggest something like:
var Placeholder = (function() 
{
    /** 
     * A boolean indiciating the browser support for the
     * placeholder attribute. 
     */
    this.native_support = (function() {
        var input = document.createElement("input");
        return ("placeholder" in input);
    })();
    
    /**
     * Adds a placeholder value on the specified input.
     */
    this.Add = function(input, placeholder) {
        if (!this.native_support) {
            input = $(input);
            
            input.focus(function() {
                if (input.val() == placeholder) {
                    input.val('');
                    input.css({'color' : '#000000'});
                }
            });
            
            input.blur(function() {
                if (input.val() == '') {
                    input.val(placeholder);
                    input.css({'color' : '#C0C0C0'});
                }
            });
            
            input.blur();
        }
    }
    
    /* Enables the placeholder values set on input elements  
     * in browsers that do not support it. */
    $(function() {
        if (!Placeholder.native_support) {
            $("input[placeholder]").each(function() {
                Placeholder.Add($(this), $(this).attr("placeholder"));
            });
        }
    });
    
    return this;
})();


This would create a Placeholder object that automatically sets the jQuery events on inputs that have the placeholder attribute set on browsers that do not support it, effectively making it so that the placeholder attribute is cross-browser compatible in sites that include this script.

Edit:
Turns out this is coming in quite handy on my current project :D
But I needed to get rid of the jQuery dependency, and I made it stop sending the placeholder value if nothing is set, which resulted in this snippet:

Spoiler

This post has been edited by Atli: 17 September 2011 - 11:18 PM

Was This Post Helpful? 3
  • +
  • -

#4 EnvXOwner  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 357
  • View blog
  • Posts: 2,319
  • Joined: 10-August 09

Posted 18 September 2011 - 05:52 AM

Wow man. That's epic! I'm still fairly new to jQuery and Javascript (I know basic things), I'm still learning a lot. I'll be using what you said though to learn off of. I thought that this would be interesting to make as it was testing my skills and was going to help me on a project :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1