Created
September 27, 2012 00:16
-
-
Save twright/3791433 to your computer and use it in GitHub Desktop.
Add a placeholder to a textfield
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function() { | |
// Select the field we want to add the behaviour to | |
var field = jQuery('#respond input[type="text"][name="ecf_4"]'); | |
// What text do we want to | |
var placeholder_text = 'your placeholder'; | |
var text_changed = false; | |
if ('placeholder' in field[0]) | |
/* Modern browsers natively support text field placeholders */ | |
field.attr('placeholder', placeholder_text); | |
else { | |
/* For older browsers we can fake it using JavaScript event handlers */ | |
// Set the initial text to the placeholder | |
field.val(placeholder_text); | |
// Keep track of whether the user has changed the text of the field | |
field.change(function() { | |
if (!(text_changed || $(this).val() === '')) | |
text_changed = true; | |
else if (text_changed && $(this).val() === '') | |
text_changed = false; | |
}); | |
// Clear the text on focus if it has not been changed by the user | |
field.focus(function() { | |
if (!text_changed) | |
jQuery(this).val(''); | |
}); | |
// Put the placeholder back if the user has not changed the text | |
field.blur(function() { | |
if (!text_changed) | |
jQuery(this).val(placeholder_text); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment