Placeholder plug-in detailed

Source: Internet
Author: User
Tags define local

The placeholder plugin is used to implement input or textarea text box display default text, when the focus is obtained, the default text disappears. The user presses the DELETE key, the input character deletes, and loses the focal point, the default text also appears and so on function. With this plugin, only $ ("input") is required. placeholder (); This input element must have the placeholder attribute, which is the text that input defaults to display. And there is no placeholder value in the class attribute value in the INPUT element, and this plugin is also based on jquery.

Before looking at the source code, I would first say a knowledge point:

If we use. Click ()/. Bind (' click ') plus. Unbind (' click ') to repeat the binding, the Unbind will be all the click handlers bound to the element. Potentially affecting the behavior of the element in other third parties (for example, there is another plug-in that also binds the element's click event). Of course, if the name of the function is explicitly defined in bind, you can provide the function name as the second parameter unbind one of the processing functions in the Unbind, but in practical applications we will likely encounter various cases of anonymous function binding.

For this problem, the solution for jquery is to use the namespace of event bindings. That is, after the event name, add the. Something to differentiate yourself from this part of the behavior logic scope.
For example, use. bind (' Click.mycustomroutine ', function () {...}); The same thing is to bind the anonymous function to the click event (you can bind the different anonymous handlers multiple times with your own namespace), and when Unbind, use. Unbind (' Click.mycustomroutine ') to release all bindings to. Mycustomroutine The Click event of the namespace without releasing the Click event handler that is bound by the. bind (' click ') or another namespace.
At the same time, using the command space allows you to unbind all event bindings under this namespace at once, via. Unbind ('. Mycustomroutine ').
It is important to note that jquery namespaces do not support multi-level spaces. So in jquery, if you use. Unbind (' Click.myCustomRoutine.myCustomSubone '), the namespace is Mycustomroutine and Mycustomsubone, respectively. All click events under the two side-by-side namespace, instead of the Mycustomsubone subspace under Mycustomroutine.

Next we look at the source code:

var isinputsupported = ' placeholder ' in document.createelement (' input ') ;  
var istextareasupported = ' placeholder ' in document.createelement (' textarea ');  
var prototype = $.fn;   //jquery prototype Object
// The object that resolves browser compatibility, which has many properties, such as: Option,select,radio,checkbox, which is an object with a set or get method to solve the browser compatibility problem. The value values for these 4 elements are handled in jquery for compatibility.
var hooks;
var placeholder;

if (isinputsupported && istextareasupported) { //If the browser is supported by default, add the placeholder method directly in the JQuery prototype object, So the jquery object can call the placeholder method.

placeholder = Prototype.placeholder = function () {
return this; //this actually refers to the jquery object, $ ("input")
};

Placeholder.input = Placeholder.textarea = true; //Add two attributes to the placeholder method, and the property value is True

} else {

placeholder = Prototype.placeholder = function () {
var $this = this;
$this. Filter (

(isinputsupported?) ' TextArea ': ' input ') + ' [placeholder] ' //If support for input palceholder, is textarea[placeholder], if not supported, that is: input[ PLACEHOLDER]. Filter out these elements for the next step, either the TEXTAREA element with the placeholder attribute or the form element with the placeholder attribute (: The input selector selects the form element).

). Not ('. Placeholder '). Bind ( //delete element with placeholder in class attribute value )

{
' Focus.placeholder ': Clearplaceholder, //Bind focus and Blur event, namespace for placeholder, convenient for unbind when unbinding, use.
' Blur.placeholder ': Setplaceholder
}

). Data (' placeholder-enabled ', true) //To add placeholder-enabled to true for these elements in the cache system

. Trigger (' Blur.placeholder '); //Trigger Blur.placeholder event, execute Setplaceholder method. That is, by default, the mouse focus is not in the input box, so the blur event of input is triggered
return $this;
};

Placeholder.input = isinputsupported;
Placeholder.textarea = istextareasupported;

Hooks = { //define local variable hooks

' Set ': function (element, value) { ///If the placeholder is set for the password box, then the element here is the new INPUT element, if it is for a normal input box, Then the element here is the normal INPUT element, where value is the default text
var $element = $ (element);

var $passwordInput = $element. Data (' Placeholder-password ');   //If it is a password box, then the Placeholder-password value of the new input is the Password box object, and if it is a normal INPUT element, it returns undefined.
if ($passwordInput) {
$passwordInput [0].value = value;  //Set Password box value value

if (! $element. Data (' placeholder-enabled ') { //If it is a normal INPUT element, $element. Data (' placeholder-enabled ') returns True, Reverse returns false, and therefore does not enter the IF statement.
return element.value = value;

Element.va Lue = value;
return $element;

};

if (!isinputsupported) { //If the browser does not support the placeholder event of input, enter the IF statement
Valhooks.input = hooks; //To add the Input Property object to jquery, to solve the browser INPUT element setting value and value compatibility problem, originally valhooks only radio,checkbox,select,option these four properties, now more input.
}
if (!istextareasupported) { //If the TextArea placeholder event is not supported, enter the IF statement
Valhooks.textarea = hooks; //Resolution of compatibility issues for setting values and values for textarea elements
}

}

function args (elem) { //elem is the input element, for ie6-7
var newattrs = {};
var rinlinejquery =/^jquery\d+$/;
$.each (elem.attributes, function (i, attr) { //Take the INPUT element's Attributes Property object
if (attr.specified &&!rinlinejquery.test (attr.name)) { //If the property value is explicitly set by the user, then its specified will be true and the The sex name is not a custom attribute of jquery (the data method is called on the element, and a custom attribute with a jquery start + random number is added to the element when you add it to the jquery cache system)
Newattrs[attr.name] = Attr.value; //Put these explicitly set property values into a JSON object and return.
}
});
return newattrs;
}

function Clearplaceholder (event, value) { //When the mouse focus is on the INPUT element

var input = this;
var $input = $ (input);
If (Input.value = = $input. attr (' placeholder ') && $input. Hasclass (' placeholder ')) { //If the text of input is the default text, And when there is a placeholder value in the class attribute, enter the IF statement, if the user enters the default text in input and then triggers the Blur event, then the placeholder class of input is deleted, so when you trigger the focus event again, Does not enter the IF statement
if ($input. Data (' Placeholder-password ')) { //If it is a password box, the input here is actually inputnew, because input has already been hide.
$input = $input. Hide (). Next (). Show (). attr (' id ', $input. REMOVEATTR (' id '). Data (' Placeholder-id ')); //Hide the inputnew, take the INPUT element, display it, and restore the ID of the INPUT element. Also remove the ID of the inputnew and get the value of Placeholder-id in the Inputnew cache system (this value is the value of the previous INPUT element ID), assigned to the ID of the INPUT element.
$input. focus (); the//input element gets the focus (then input is the input to the password box)
} else { //If it is not a password box
input.value = ""; //The text in input is emptied
$input. Removeclass (' placeholder '); //And remove this placeholder class
input = = Safeactiveelement () && input.select (); //Solve a bug under IE9, because IE9, if the element in the IFRAME gets the focus, you call DOCUMENT.ACTIVEELEMENT,IE9 to throw an error. Therefore it must be handled with Try,catch, if an error is thrown, the Select method of the element is not executed (this method selects the text in the input box), and if no error is thrown, the Select method of input is executed (the return value is undefined).
}
}
}

function Setplaceholder () { //Lose Focus trigger Blur event
var $replacement;
var input = this; //this refers to the INPUT element
var $input = $ (input); //Convert to jquery object
var id = this.id; //Take the ID of the INPUT element

if (Input.value = = "") { //If the input box is an empty string
if (input.type = = ' password ') { //If input is a password input box
If (! $input. Data (' Placeholder-textinput ') { //input element has placeholder-textinput attribute value in the jquery cache system and does not enter the IF statement
try {
$replacement = $input. Clone (). attr ({' type ': ' Text '}); //Clone an INPUT element, we name it inputnew, and set its Type property to text. Old version of IE will be error, cannot modify the type value of the cloned input
} catch (e) {
$replacement = $ (' <input> '). attr ($.extend (args (this), {' type ': ' Text '})); //Remove all explicitly set properties of this input element and extend the Type property. All of these attributes are then assigned to the newly created INPUT element, which we named Inputnew
}
$replacement. Removeattr (' name '). Data ({ //Remove the name attribute of the Inputnew element and add data to the jquery data cache system )
' Placeholder-password ': $input,
' Placeholder-id ': ID
}). bind (' Focus.placeholder ', clearplaceholder); //Bind the focus event to this inputnew element.
$input. Data ({ //To add data to the jquery cache system for the INPUT element
' placeholder-textinput ': $replacement,
' Placeholder-id ': ID
}). before ($replacement); //Add inputnew element in front of element input
}
$input = $input. Removeattr (' id '). Hide (). Prev (). attr (' ID ', id). Show (); //Remove the id attribute of the INPUT element and hide it, get the element that precedes the input element, that is, the inputnew element, then set its ID and let it appear.
}
$input. addclass (' placeholder '); //If the original input is a password box, here the input is inputnew, if not the password box, here is the original input.
$input. Val ($input. attr (' placeholder ')); //Here, if the browser's input or textarea does not support the placeholder event, the hooks defined above will be called to set the value. For details, see Hook's Set method. Why do you want to create a new INPUT element here, because the INPUT element on the page is a password box, and when you enter the text, the character is displayed, but by default, the default text should be displayed, so a new INPUT element is created, the Password box is hidden, The default text is then placed inside the new INPUT element. When the user clicks with the mouse, the new input receives the focus, the new INPUT element will be hidden, while the password box is displayed, so that the user input characters will be * * * this, if not create a new input, then the default text in the Password box is displayed in * * *.
} else { //If the value of input is not "", the placeholder class name of input is removed
$input. Removeclass (' placeholder ');
}
}

function Safeactiveelement () {
try {
return document.activeelement; //http://bugs.jquery.com/ticket/13378
} catch (Exception) {}
}

Come on!

Placeholder plug-in detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.