Skip to content

Instantly share code, notes, and snippets.

@emohamed
Created September 13, 2012 09:36
Show Gist options
  • Select an option

  • Save emohamed/3713218 to your computer and use it in GitHub Desktop.

Select an option

Save emohamed/3713218 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<title>PlaceHolders demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.do_placeholders();
});
jQuery.fn.do_placeholders = function() {
var browser_supports_placeholder = !!("placeholder" in (document.createElement('input')));
if (browser_supports_placeholder) {
return;
}
this.each(function() {
// Do not re-initialize
if ($(this).data("did_placeholder")) {
return;
}
var original_value = this.value;
if (original_value == '') {
this.value = this.getAttribute('placeholder');
}
$(this).data("did_placeholder", true);
});
$(document).on('focusin', this.selector, function() {
if (this instanceof Document) {
return;
}
if(this.value == this.getAttribute('placeholder')) {
this.value = '';
}
}).on('focusout', this.selector, function() {
if(this.value == '') {
this.value = this.getAttribute('placeholder');
}
});
}
jQuery.do_placeholders = function ( ) {
$('input[placeholder], textarea[placeholder]').do_placeholders();
}
</script>
</head>
<body>
<form action="" method="get" accept-charset="utf-8">
<strong>Inputs with placeholders:</strong><br />
<input type="text" value="" placeholder="I'm a placeholder"><br />
<input type="text" value="I'm a value" placeholder="I'm a placeholder">
<hr />
<strong>Textareas with placeholders:</strong><br />
<textarea placeholder="I'm a placeholder"></textarea><br />
<textarea placeholder="I'm a placeholder">I'm a value</textarea><br />
<hr />
<strong>Inputs without placeholders:</strong><br />
<input type="text" value=""><br />
<input type="text" value="I'm a value">
<hr />
<strong>Textareas without placeholders:</strong><br />
<textarea></textarea><br />
<textarea>I'm a value</textarea><br />
<hr />
<strong>Dynamic input with placeholder</strong>
<div id="dynamic-input-holder">
</div>
<script type="text/javascript">
setTimeout(function () {
var input = $("<input>", {
"type": "text",
"placeholder": "I'm a placeholder",
"value": ""
});
$('#dynamic-input-holder').append(input);
$(input).do_placeholders();
}, 150);
</script>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment