Well to begin i would like to mention that the aim of this question is not to ask how it is done but rather understand why the way i did it works.
I wanted to create placeholder texts for form elements and while playing with jquery i came up with the following code:
function placehold(id,placeholder) // id of element and placeholder text
{
$("#"+id).val(placeholder); //initialize form field
$("#"+id).focusin(function() //on focus
{
if ($(this).val()==(placeholder))
{
$(this).val(null);
/*if input's value is placeholder then em开发者_高级运维pty
input and wait for value */
}
});
$("#"+id).focusout(function() //on lost focus
{
if ($(this).val()==(""))
{
$(this).val(placeholder); //reset val to placeholder text if empty
}
});
}
And this will work even if i call the function on several fields, like,
placehold('uname','Please enter a username');
placehold('pword','Please enter a password);
placehold('email','Please enter an email address');
in the above case it will work in all 3 textboxes as expected, and herein lies my question: Where are the different placeholders stored during runtime? is an instance of the function kept for each field it is bound to? if yes Would that have any implications on performance in the long run?
Thank you for your time and help :)
is an instance of the function kept for each field it is bound to?
Yes. For every time you call placehold()
, new event handler functions are created. The values of id
and placeholder
are kept as part of the closures you create.
if yes Would that have any implications on performance in the long run?
The way you did it, there is a little overhead associated with every element that you call placehold()
on. I would not worry about that, though, it really is negligible.
Nicer would be to re-use the event-handling functions:
function placeholderEmpty() {
var $this = $(this);
if ( $this.val() == $this.data("placeholder") ) {
$this.val("");
}
}
function placeholderDefault() {
var $this = $(this);
if ( $this.val() == "" ) {
$this.val( $this.data("placeholder") );
}
}
function placehold(id,placeholder) {
$("#"+id).data("placeholder", placeholder)
.focusin(placeholderEmpty)
.focusout(placeholderDefault)
.trigger("focusout");
}
The next step would be a plugin (note the use of another closure):
$.fn.extend({
placehold: function () {
var placeholderEmpty = function () { /* ... */ };
var placeholderDefault = function () { /* ... */ };
return function(placeholder) {
this.data("placeholder", placeholder)
.focusin(placeholderEmpty)
.focusout(placeholderDefault)
.trigger("focusout");
return this;
}
}();
});
use as
$('#uname').placehold('Please enter a username');
$('#pword').placehold('Please enter a password');
$('#email').placehold('Please enter an email address');
$('.manyTextFields').placehold('All get the same text & behavior.');
精彩评论