The _javascript technique of realizing statistic character and local storage function of JS imitation micro-Blog

Source: Internet
Author: User
Tags chrome developer jquery library hasownproperty

With the popularity of mobile devices and Web applications, in order to better facilitate the use of users, the Web page or application of the user experience requirements are more and more high, it is true, as users prefer to choose the user experience good results of the site or application, so as a developer we need to develop a more life-like application.

Believing that many people have the experience of using Weibo, a social platform such as Weibo, a good user experience becomes particularly important.

For example: We in the microblogging, the text box will prompt us in real time the number of characters left, so that user-friendly tips to facilitate users know the micro-blog word limit, but also limited the user's input words.

One sentence we should bear in mind is: all input, there must be restrictions;

In the following article, we will describe how to implement the live prompt for input characters and local storage (localstorage) technology.

1, jquery character Statistics plugin
Now, we use the Sina Weibo to send the micro-blog input box as an example, introducing using jquery to implement real-time prompts the user the number of characters remaining.

Sina Weibo is limited to 140 Chinese (280 English), of course there are a variety of other characters spaces case, before the user input to reach the limit or reached, a good user experience should prompt the user to approach or reach the limit, of course, we can use different colors or bold font to prompt the user.

Figure 1 User input restrictions on Sina Weibo

Character Count the plug-in creates a sibling span after the input box to display the current number of characters remaining, modifying the remaining characters in span in real time when the KeyUp, KeyDown, and change events of the input box are triggered, if the number of remaining characters is close to "warning" (nearly 0) modify the CSS style to prompt the user to approach the input limit.

When the remaining characters reach "warning", add the corresponding style class to the span element, and when the remaining characters are equal to or greater than the input limit, adding the corresponding style class prompts the user to exceed the character limit.

We dynamically insert the following code into the page by using the character Count plugin:

<!--adds element dynamic-->
<span class= "Counter" >140</span>

By default, the character limit is 140, when the number of characters that can be entered is less than or equal to 25 prompts the user, and when the number of characters that can be entered is less than 0 o'clock, the number of characters is prompted to exceed the limit. Here we define the conditional object by default:

The default limitation.
var defaults = {
 allowed:140,
 warning:25,
 CSS: ' counter ',
 counterelement: ' span ',
 csswarning: ' Warning ',
 cssexceeded: ' exceeded ',
 countertext: '
};

Above, we have defined the defaults object, it contains allowed, warning, CSS, csswarning and cssexceeded attributes, by modifying the Defaults object properties, we can easily modify the character statistics plug-in.

    • Allowed: The number of characters allowed to enter.
    • Warning: Prompts the user the number of characters remaining close to 0.
    • CSS: A CSS style class name added to the counter element.
    • Csswarning: Warning hint style.
    • cssexceeded: The character limit hint style is exceeded.

Next, we define the method calculate () in the character Statistics plug-in, which calculates the current number of characters remaining and, if the warning range is reached, adds the style class "warning" to the page, adding the style "exceeded" to the page when the remaining characters are less than or equal to zero.

/***
* Calculates the char
* @param obj
*
/function Calculate (obj) {//Get the

 count.
 var count = GetLength ($ (obj). val ());
 var available = Options.allowed-count;

 if (available <= options.warning && available >= 0) {
  $ (obj). Next (). addclass (options.csswarning);
 }
 else {
  $ (obj). Next (). Removeclass (options.csswarning);
 if (available < 0) {
  $ (obj). Next (). addclass (options.cssexceeded);
 }
 else {
  $ (obj). Next (). Removeclass (options.cssexceeded);
 $ (obj). Next (). HTML (options.countertext + available);


We also define the method GetLength (), when the input character is Chinese Totlen plus 1, if it is an English character or a number Totlen plus 0.5 (the default allows 140 Chinese characters).

/**
* Get the length of char.
* @param str
* @return {number}
*
/function GetLength (str) {
 var totlen = 0;
 for (var i = 0; i < str.length i++) {
  //If the ' char is Chinese.
  if (Str.charcodeat (i) > 256) {
   Totlen = 1;
  }
  else {
   Totlen + = 0.5;
  }
 }
 return Math.floor (Totlen);
}

Next, we bind the KeyUp (), KeyDown () and Change () event methods in the control, and when the Page object triggers the KeyUp (), KeyDown (), or the Change () event method, the Calculate () method is invoked to calculate the number of characters currently remaining. and add the corresponding CSS style to the page.

Binds text area KeyUp, KeyDown and Change event.
This.each (function () {
 $ (this). After (' < ' + options.counterelement + ' class= ' + options.css + ' "> ' + options.c Ountertext + ' </' +
    options.counterelement + ' > ');
 Calculate (this);
 $ (this). KeyUp (function () {calculate (this), Storeweibo (This)});
 $ (this). KeyDown (function () {calculate (this), Storeweibo (This)});
 $ (this). Change (function () {Calculatea (This)});

2, Web Storage
Now, we have basically implemented the jquery character count plug-in function, I believe a lot of people have noticed that if we don't send Twitter on Twitter the next time we open the page, the Send box still keeps the tweets we haven't sent, even if we close the browser and reopen the page, the message we don't send is still there.

In fact, to achieve this functional approach is a variety of, such as we can use: cookies,session technology.

With the development of the HTML5 specification, the consortium has developed a specification for networked storage (Web Storage) that provides the ability to store data in the client until the session expires (sessions are stored) or exceeds local capacity (local storage), which is more powerful than traditional cookie storage. Easier to implement and larger capacity (most browsers support 5M of local storage).

Session Storage
Session Storage: It saves data in a session, and once we close the browser tab, the data in the session is invalidated.

Local storage
Local Storage: When the data needs to be persisted to the client, we can use local storage (native Storage), which stores the data in the form of key/value, and if the page or browser is closed, reopening the page data remains. It provides a lasting preservation of the data. A simple application is to record the number of times a user accesses a page.

Figure 2 Comparison of storage space

Next, we'll explain how to save user data using local storage.

Because, Localstorage provides SetItem (), GetItem (), RemoveItem (), key () and clear () 5 methods, and a property length, which is defined as follows:

Storage definition.
Interface Storage {
 readonly attribute unsigned long length;
 Domstring key (in unsigned long index);
 Getter any getitem (in Domstring key);
 Setter creator void SetItem (in Domstring key, in any value);
 deleter void RemoveItem (in domstring key);
 void Clear ();

Using local storage in a modern browser is very simple, and we just need to call the Localstorage object's methods or properties directly in the JavaScript code to OK.

Stores the username ' Jkrush ',
//Then get the username.
Localstorage.setitem (' username ', ' jkrush ');
var userName = Localstorage.getitem (' UserName ');

Above, we implement data storage and acquisition by calling Localstorage's SetItem () and GetItem () methods, because Localstorage store data in key/value form, so we need to provide key/value value when storing. Then call the GetItem () method to get the value stored in the key.

Since local storage is stored as key/value, we can easily store string-type data, and local storage is stretched if we need to store object types.

Let's say we're storing a student object in the Localstorage, and the specific code is as follows:

Defines a student object.
var student = {
 name: ' Jk_rush ', age
 : ' num ',
 sex: ' Male '
};

Prints Student Object
console.log (student);

Stores Student object.
Gets student object again.
Localstorage.setitem (' student ', student);
Console.log (Localstorage.getitem (' student '));

Figure 3 Localstorage Storage objects

From the example above, we notice that the output in the Firebug console is not the real student object, but the information of the student object.

So how do we store objects in the Localstorage? In fact, we can serialize objects into JSON data for storage, and finally convert the JSON data into objects via deserialization. Specifically implemented as follows:

Defines a student object.
var student = {
 name: ' Jk_rush ', age
 : ' num ',
 sex: ' Male '
};

Console.log (student);

Serializes the object to JSON string.
Localstorage.setitem (' Student ', json.stringify (student));

Deserializes the JSON string to object.
Console.log (Json.parse) (Localstorage.getitem (' student '));

In the example above, before storing the student object, we use the JSON stringify () method to serialize the object as a JSON string and then store it in the localstorage; if we want to get the student object, just use the JSON parse () method to deserialize a string as an object.

Figure 4 Localstorage Storage objects

Above, we implemented the student object conversion to the JSON format string stored in the Localstorage, next, we add the Localstorage function in the previous example, the specific code is as follows:

/** * Store user data into the local storage.
 * @param obj */function Storeweibo (obj) {//Checks the browser supports local storage or.
 if (window.localstorage) {localstorage.setitem (' Publishertop_word ', $ (obj). val ());
  else {//For instance, ie 6 and 7 don't support local storage,//So we need to provider other way.
    Window.localstorage = {Getitem:function (SKey) {if (!skey | |!this.hasownproperty (sKey)) {return null;} Return unescape (Document.cookie.replace, New RegExp (?: ^|. *;\\s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\=\\s* ((?: [^;] (?!;)) *[^;]?).
   *), "$"); }, Key:function (Nkeyid) {return unescape (Document.cookie.replace/\s*\= (?:. (?!;)) *$/, ""). Split (/\s*\= (?: [^;] (?!;)) *[^;]?;\
   s*/) [Nkeyid]);
    }, Setitem:function (SKey, svalue) {if (!skey) {return;} Document.cookie = Escape (SKey) + "=" + Escape (svalue) + "; Expires=tue, 2038 03:14:07 GMT;
    path=/"; This.length = document.cookie.maTCH (/\=/g). length;
    }, Length:0, Removeitem:function (SKey) {if (!skey | |!this.hasownproperty (sKey)) {return;} Document.cookie = Escape (SKey) + "=; Expires=thu, 1970 00:00:00 GMT;
    path=/";
   this.length--; }, Hasownproperty:function (SKey) {return (?: ^|;\
   \s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\= "). Test (Document.cookie);
  }
  };
 Window.localStorage.length = (Document.cookie.match (/\=/g) | | window.localstorage). length;

 }
}

Now in the custom character statistics plug-in (jquery.charcount.js), Add Method Storeweibo (), first we determine whether the current browser support Localstorage, mainstream browsers such as: Chrome, Firefox, Opera , Safari, and IE 8 support both local storage (Localstorage) and session storage (Sessionstorage).

If the browser supports local storage, then we can directly call the Localstorage SetItem () method to store the data in textarea, and when we open the page or browser again, we first check to see if the Localstorage store the corresponding data. If there is a data store, then again we take the data out and display it in the textarea.

However, since some users may use older browsers (such as: IE6 and IE7), we must provide a solution to support older browsers, considering compatibility.

We know that older browsers, such as IE6 and IE7, support cookies for persistent storage, so we use cookies to implement GetItem (), SetItem () and RemoveItem () methods.

Figure 5 Mainstream browsers support Web Storage

Now that we have completed the character statistics plugin jquery.charcount.js, because of the time we have the interface of the Send box has been designed, the specific HTML code is as follows:

<!--from design-->
<body>
 <form id= "form" method= "POST" >
  
 

Figure 6 Interface design of the sending box

Next, we refer to the jquery library and the custom character statistics plug-in jquery.charcount.js in the page code as follows:

<!--Adds Javascript reference--> <script type= "Text/javascript" src=
/libs/jquery/1.6.1/jquery.min.js "></script>
<script type=" Text/javascript "src="./js/ Jquery.charcount.js "></script>

Above, we directly refer to the jquery library provided by Google, of course, we also download the jquery library to the local, and then introduced to the project, then we add the code to call the character statistics plug-in in the HTML page, the specific code is as follows:

 <!--when document ready invokes CharCount function-->
<script type= "Text/javascript" >
 $ (document ). Ready (function () {
  //Uses default setting.
  $ ("#weiboMsg"). CharCount ();
</script>

Above, we have finished calling the character statistics plugin in the page code, and whenever we enter characters in the text box, we will display the remaining characters in real time, and the characters we enter in the text box will be saved to localstorage.

Next, we look at the data stored in Localstorage in Chrome and Firefox respectively.

First, we open the Chrome Developer tool (Ctr+shift+i) and we select the "Resources" option, where we can see the data saved in Localstorage.

Figure 7 Local storage for Chrome

Again, we turn on Firefox's "Firebug" (F12) and then we choose the DOM option, where we need to look for the object localstorage of the window so that we can see the data saved in the Localstorage.

Figure 8 Firefox local storage

We know that IE8 is also supporting Localstorage objects, but I did the test when I found that IE8 always hint Localstorage object undefined, then I stackoverflow check it, some people say in IE8, The Localstorage object is dependent on the domain name, so you need to run it in the Web server to successfully save the data to Localstorage.

We note that Weibo uses local storage technology to save the user's data in the Send box, and to save the user's input once the data has been sent to empty the local store.

This article introduces how to define jquery character statistics plug-in and local storage technology by using the Micro-blog Send box example, first of all, we know that restricting user input is necessary, but how to effectively and humanized prompt user to enter restrictions? Here we have to define a jquery plug-in, dynamic statistics of the number of remaining characters, I hope that we learn JavaScript programming inspiration.

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.