Implementation of parallel microblog character statistics and Local Storage

Source: Internet
Author: User
Tags jquery library hasownproperty
1.1.1 Summary

With the popularization of mobile devices and Web applications, for better convenience for usersProgramAs a result, users prefer websites or applications with good user experience, therefore, as developers, we need to develop more personalized applications.

I believe that many people have the experience of using Weibo. A social platform like Weibo makes a good user experience especially important.

For example, when we are sending Weibo posts, the text box will prompt us the number of remaining characters in real time. This kind of user-friendly prompt makes it easier for users to know the word limit on Weibo and also limits the number of words entered by users.

One sentence should be kept in mind: all inputs must be limited; all inputs must be verified.

In the next blog, we will introduce how to implement the real-time prompt function of input characters and the local storage technology.

Contents
    • Jquery character statistics plug-in
    • Web Storage
1.1.2 text jquery character statistics plug-in

Now, we use Sina Weibo's Weibo input box as an example to introduce how to use jquery to display the remaining characters in real time.

Sina Weibo is limited to 140 Chinese characters (280 English letters). Of course there are various other characters with spaces, which can be reached before the user input reaches the limit, A good user experience should prompt that the user is approaching or has reached the limit. Of course, we can use different colors or bold fonts to prompt the user.

Figure 1 Sina Weibo user input restrictions

The Character Count statistics plug-in creates a span with the same level element after the input box. It is used to display the number of remaining characters. When the keyup, keydown, and change events in the input box are triggered, modify the number of remaining characters in the span in real time. If the number of remaining characters is close to "warning" (close to zero), modify the CSS style to prompt that the user is close to the input limit.

When the remaining characters reach "warning", add the corresponding style class to the span element. When the remaining characters are equal to or greater than the input limit, the corresponding Style Class prompts that the user has exceeded the Character Count limit.

We dynamically Insert the following in the page through the Character Count statistics plug-in:Code:

 
<! -- Adds element dynamic --><SpanClass= "Counter">140</Span>

By default, the maximum number of characters is 140. When the number of characters can be entered is less than or equal to 25, the user is prompted. When the number of characters can be entered is less than or equal to 0, the number of user characters exceeds the limit. Next we define the default condition object:

// The default limitation.VaRDefaults = {allowed: 140, warning: 25, CSS:'Counter', Counterelement:'Span', Csswarning:'Warning', Cssexceeded:'Exceeded', Countertext:''};

The above defines the ults object, which contains allowed, warning, CSS, csswarning, cssexceeded and other attributes. By modifying the attributes of the defaults object, we can easily modify the character statistics plug-in.

Allowed: number of characters that can be entered.

Warning: indicates that the number of remaining characters is close to zero.

CSS: name of the CSS style class added to the counter element.

Csswarning: Warning style.

Cssexceeded: Specifies the style when the character limit is exceeded.

Next, we define the method calculate () in the character statistics plug-in to calculate the number of remaining characters. If the warning range is reached, add the Style Class "warning" to the page ", when the remaining characters are less than or equal to zero, add the style "exceeded" to the page ".

/***** Calculates the char * @ Param OBJ */FunctionCalculate (OBJ ){// Get the count.VaRCount = getlength ($ (OBJ). Val ());VaRAvailable = options. Allowed-count;If(Available <= options. Warning & available> = 0) {response (obj).next().addclass(options.css warning );}Else{Certificate (obj).next().removeclass(options.css warning );}If(Available <0) {certificate (obj).next().addclass(options.css exceeded );}Else{Export (obj).next().removeclass(options.css exceeded);} export (obj).next().html (options. countertext + available );}

We also define the getlength () method. When the input character is Chinese, totlen is added with 1. If it is an English character or number, totlen is added with 0.5 (140 Chinese characters are allowed by default ).

 
/*** Get the length of char. * @ Param Str * @ return {number }*/FunctionGetlength (STR ){VaRTotlen = 0;For(VaRI = 0; I <Str. length; I ++ ){// If the char is Chinese.If(Str. charcodeat (I)> 256) {totlen + = 1 ;}Else{Totlen + = 0.5 ;}}ReturnMath. Floor (totlen );}

Next, we bind the keyup (), keydown (), and change () event methods to the control. When the Page Object triggers the keyup (), keydown (), or change () event method, call the calculate () method to calculate the number of remaining characters 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. countertext + '</' + Options. counterelement + '>' ); Calculate ( This ); $ ( This ). Keyup (Function () {Calculate ( This ), Storeweibo ( This )}); $ ( This ). Keydown ( Function () {Calculate ( This ), Storeweibo ( This )}); $ ( This ). Change ( Function () {Calculatea ( This )});});
Web Storage

Now, we have basically implemented the jquery Character Count statistics plug-in function. I believe many people have noticed that if we don't send Weibo posts to open the page next time, the sending box still saves the posts we haven't sent. Even if we close the browser and re-open the page, the messages we haven't sent still exist.

In fact, there are many ways to implement this function. For example, we can use cookies, sessions, and other technologies.

Along with the HTML5 specification, W3C has developed the Web storage specification, which stores data on the client until the session expires (Session storage) or exceeds the local capacity (local storage), which is more powerful, easier to implement, and larger than traditional cookies (most browsers support 5 MB local storage ).

Session Storage

Session storage: stores data in sessions. Once the browser tab is closed, the data in the session becomes invalid.

Local Storage

Local Storage: when the data needs to be permanently stored in the client, we can use local storage to store the data in the form of key/value, if the page or browser is closed and the data on the page is reopened, it provides persistent data storage. A simple application is to record the number of times a user accesses a page.

Figure 2 Comparison of buckets

Next, we will introduce how to use local storage to save user data.

Localstorage provides five methods, namely setitem (), getitem (), removeitem (), key (), and clear (), and an attribute length. The specific definitions are as follows:

// Storage definition.InterfaceStorage {readonly attribute unsignedLongLength; domstring key (InUnsignedLongIndex); getter any getitem (InDomstring key); setter creatorVoidSetitem (InDomstring key,InAny value); deleterVoidRemoveitem (InDomstring key );VoidClear ();};

It is very simple to use local storage in modern browsers. We only need to call the method or attribute of the localstorage object directly in JavaScript code.

// Stores the username 'jkrush', // then get the username.Localstorage. setitem ('Username','Jkrush');VaRUsername = localstorage. getitem ('Username');

Above, we can store and obtain data by calling the setitem () and getitem () Methods of localstorage. Because localstorage stores data in the form of key/value, therefore, we need to provide the key/value during storage, and then call the getitem () method to obtain the value stored in the key.

Because local storage is stored in the form of key/value, we can easily store string-type data. If we need to store object types, local storage is too slow.

Suppose we store a student object to localstorage. The specific code is as follows:

// Defines a student object.VaRStudent = {Name:'Jk _ rush', Age:'26', Sex:'Male'};// Prints student objectConsole. Log (student );// Stores student object. // gets student object again.Localstorage. setitem ('Student', Student); console. Log (localstorage. getitem ('Student'));

 

Figure 3 localstorage storage object

Through the above example, we noticed that the output in the firebug console is not a real student object, but the information of the student object.

So how can we store objects in localstorage? In fact, we can serialize the object into JSON data for storage, and finally convert the JSON data into an object through deserialization. The specific implementation is as follows:

// Defines a student object.VaRStudent = {Name:'Jk _ rush', Age:'26', 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 above example, before storing the student object, we use the stringify () method of JSON to serialize the object as a JSON string and store it in localstorage. If we want to obtain the student object, you only need to use the JSON parse () method to deserialize the string as an object.

 

Figure 4 localstorage storage objects

The preceding Code converts a student object to a string in JSON format and stores it in localstorage. Next, we add the localstorage function in the previous example. The specific code is as follows:

 /*** Store user data into local storage. * @ Param OBJ */  Function Storeweibo (OBJ ){ // Checks the browser supports local storage or not.  If (Window. localstorage) {localstorage. setitem ( 'Herhertop _ word' , $ (OBJ). Val ());} Else { // For instance, ie 6 and 7 do not 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 *((? : [^;] (?!;) * [^;]?). *" ), "$1" );}, 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, 19 Jan 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, 01 Jan 1970 00:00:00 GMT; Path = /" ; This . Length --;}, hasownproperty: Function (Skey ){ Return ( New Regexp ( "(? : ^ |; \ S *)" + Escape (skey). Replace (/[\-\. \ + \ *]/g,"\ $ &" ) + "\ S * \ =" )). Test (document. cookie) ;}}; window. localstorage. length = (document. cookie. match (// =/G) | window. localstorage ). length ;}}

Now we are using the custom character statistics plug-in (jquery. charcount. JS), add the storeweibo () method, first we determine whether the current browser supports localstorage, mainstream browsers such: chrome, Firefox, opera, Safari, and IE 8 both support local storage and session storage ).

If the browser supports local storage, we can directly call the setitem () method of localstorage to store the data in textarea. when we open the page or browser again, first, check whether the localstorage stores the corresponding data. If there is data storage, we will retrieve the data again and display it in textarea.

However, some users may use earlier browsers (such as IE6 and IE7). Considering compatibility, we must provide solutions that support earlier browsers.

We know that earlier browsers (such as IE6 and IE7) Support persistent storage of cookies. Therefore, we use cookies to implement getitem (), setitem (), removeitem (), and other methods.

 

 

Figure 5 mainstream browsers support web Storage

Now we have completed the character statistics plug-in jquery. charcount. js. Because of the time, we have designed the sending box interface. The specific HTML code is as follows:

 <! -- From design -->  <  Body  > <  Form  ID  = "Form"  Method  = "Post"> <  H2  > What's new? </  H2  > <  Div > <  Label  Class  = "Mali_oglas_kategorija"  For  = "Message"> What's new? <  B  > </  B  > </  Label  > <  Textarea  ID  = "Weibomsg"  Placeholder = "Please enjoy fun"> </  Textarea  > <  Span  Class  = "Counter"> </  Span  > <  Input  Onclick  = "Savecache ()"  Type  = "Submit"  Value  = "Publish"> </  Div  > </ Form  > </  Body  > 

 

Figure 6 sending box Interface Design

Next, we reference the jquery Library and the custom character statistics plug-in jquery. charcount. js in the page code. The specific code is as follows:

<! -- Adds JavaScript reference --><ScriptType= "Text/JavaScript"SRC= "Http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </Script> <ScriptType= "Text/JavaScript"SRC= "./JS/jquery. charcount. js"> </Script>

Above, we directly reference the jquery library provided by Google. Of course, we also download the jquery library to a local directory and then introduce it to the project, next, we will add the code to call the character statistics plug-in on the HTML page. The specific code is as follows:

<! -- When document ready invokes charcount function --><ScriptType= "Text/JavaScript">$ (Document). Ready (Function(){// Uses default setting.$ ("# Weibomsg"). Charcount ();});</Script>

Above, we have completed calling the character statistics plug-in the page code. Whenever we enter characters in the text box, the remaining characters are displayed in real time, in addition, all characters entered in the text box are saved to localstorage.

Next, we will view the data stored in localstorage in chrome and Firefox respectively.

First, we open Chrome's "Developer tool" (CTR + Shift + I), and then we select the "Resources" option. Then we can see the data saved in localstorage.

Figure 7 chrome Local Storage

Similarly, we open Firefox's "firebug" (F12), and then we select the "dom" option, then we need to find the window object localstorage, in this way, you can see the data stored in localstorage.

Figure 8 local Firefox Storage

We know that IE8 also supports localstorage objects, but I found that the localstorage object is not defined in IE8 during the test. Later, I checked it in stackoverflow. Someone said that in IE8, the localstorage object depends on the domain name. Therefore, you must run it on the Web server to successfully Save the data to localstorage.

 

 

1.1.3 Summary

This article describes how to define the jquery character statistics plug-in and local storage technology through the Weibo sending box example. First, we know that limiting user input is required, but how can we effectively and humanly Prompt user input restrictions? Here we define a jquery plug-in to dynamically count the remaining characters.

We noticed that Weibo uses the local storage technology to save the user's data in the sending box. Once the data is sent, the local storage is cleared, and the user's input is saved.

Reference
    • Http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/
    • Https://developer.mozilla.org/en-US/docs/DOM/Storage
    • Http://msdn.microsoft.com/en-us/library/cc197062%28v=vs.85%29.aspx
    • Http://stackoverflow.com/questions/3452816/does-ie8-out-of-the-box-have-support-for-localstorage
    • Http://www.html5rocks.com/en/features/storage
    • Http://www.cnblogs.com/lhb25/archive/2012/11/30/oninput-and-onpropertychange-event-for-input.html

Download demo

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.