JavaScript suggest effect automatically accomplishes code sharing _javascript tips

Source: Internet
Author: User
Tags hash

First of all, the framework used is of course my frame mass framework, of course you can use other frameworks, such as jquery, there is nothing complicated. If you understand the principle, you can get it out at once. Presumably, you will also encounter the job of doing a search box in the future.

Because I don't have a backend, I take an object as a local database. And what I'm going to do now is far more than suggest advanced, something like IDE syntax hints. The current finished product has been placed on the GitHub.

All right, let's do this. First of all, the structure of the students can be installed in the FF Baidu home page to see the source code, when the input of a few letters, will dynamically generate those HTML. But how good, its achievement is a div placed under the search bar, inside put a table,table dynamic storage candidate words. And if the candidate is not part of the user input, that is, the part of JS that is automatically added to it will be shown in a B-label bold. However, I think the table is too heavy to quantify, instead of a list of UL, in order to let IE6 also support skim color effect, I also set up a a label inside. In order to put the word, I also added a property to it (a tag), which was used to store the vocabulary after the whole complement. It's probably like this:

Copy Code code as follows:

<div id= "Search_wrapper" >
<div>
<input id= "Search" autocomplete= "off" >
</div>
<div id= "Suggest_wrapper" >
<ul id= "Suggest_list" >
<li>
<a data-value= "complete vocabulary" href= "javascript:void (0)" >
User Input Section
<b> Auto Tip Section </b>
</a>
</li>
<li>
<a data-value= "complete vocabulary" href= "javascript:void (0)" >
User Input Section
<b> Auto Tip Section </b>
</a>
</li>
<!--more Li 10-->
</ul>
</div>
</div>

Look at the structure, in fact, is two parts, div#search_wrapper for visible, div#suggest_wrapper for "not visible" (as long as there is no LI element, it does not occupy space, show no). The input search box has an attribute autocomplete that is used to turn off the prompts that the browser brings. With regard to Data-value, this naming method is the HTML5 recommended way to define the data to be cached, data-* in the new browser into an object called a dataset. Like what:
Copy Code code as follows:

<div id= "Masaki"
data-drink= "Coffee"
Data-meal-time= "12:00" >12:00</div>

We can access it in the following ways:
Copy Code code as follows:

var el= document.getelementbyid (' Masaki ');
alert (El.dataset.drink);
alert (el.dataset.mealTime);

Of course, you can also go directly to the innertext or textcontext of a label without setting the attribute.
Note: The Full vocabulary = user Input section + Auto prompt section. Therefore, you do not add so many things in a label, to prevent the occurrence of space or something, resulting in retrieval failure!
Then the style part, but not the details. Very simple:
Copy Code code as follows:

#search_wrapper {
height:50px;
}
#search {
width:300px;
}
#suggest_wrapper {
position:relative;
}
#suggest_list {
Position:absolute;
z-index:100;
List-style:none;
margin:0;
padding:0;
Background: #fffafa;
border:1px solid #ccc;
border-bottom:0 none;
}
#suggest_list Li a{
Display:block;
height:20px;
width:304px;
Color: #000;
border-bottom:1px solid #ccc;
line-height:20px;
Text-decoration:none;
}
#suggest_list Li A:hover,. glow_suggest {
Background: #ffff80;
}

Okay, that's the point. Because I don't have a background, I want to use a local object as a local database. This object is, of course, a JS object. We iterate over the object is generally OBJ.AAA.BBB.CCC, so that all the way down, in fact, each to a point number, is used for the in loop to traverse. So we listen to the input of the text content, and when we do, we get the contents of the input box, and then we compare it in the for in loop. If the attribute begins with this input value, it is taken out, placed in an array, always fetch 10, and then the contents of these arrays are spliced into the LI element format described above and affixed to the UL element. In the middle, we also need to note that if we start by entering the point number, we take the Window object 10 attributes bar, the next encounter point number on the switch this object.
OK, start writing code, because of the use of my frame, we can go down here. On the Project home page there is a readme that teaches you how to install miniature. NET Server and view the document. In the beginning, you just take it as the Jquery,api 90% that adds the module loading function. We want to use its event module and the property module, it will be dependent on the load, and then add ready parameters, it will be executed after Domready. We select the input box for it to bind an input event, this is a standard browser is supported by the event, ie my framework is already compatible with, with jquery and native students please use the PropertyChange event simulation.
Copy Code code as follows:

by Masaki
$.require ("Ready,event,attr", function () {
var search = $ ("#search"), hash = window, prefix = "", Fixie = NaN;
Search.addclass ("Search_target");
Search.input (function () {//Listener input
Var
Input = this.value,//Original value
val = Input.slice (prefix.length),//Comparison value
output = []; Used to place output content
if (Fixie = = input) {
Return//ie is to change the value of the input box through the program will also trigger the PropertyChange event, causing us to not go up and down the operation
}
For (Var prop in hash) {
if (Prop.indexof (val) = = 0) {//Get API beginning with input value
if (Output.push (' <li><a href= "javascript:void (0)" data-value= "' +prefix +
prop+ ' > ' + input + "<b>" + (prefix + prop). Slice (input.length) + "</b></a></li>") = = 10) {
Break
}
}
}
If the point number is encountered forward, or the dot is canceled back
if (Val.charat (val.length-1) = = "." | | (Input &&!val)) {
var arr = Input.split ("."); hash = window;
for (var j = 0; J < Arr.length; J + +) {
var el = arr[j];
If (El && hash[el]) {
hash = hash[El];//reset the object to traverse the API
}
}
prefix = input = = "."? "": input;
For (prop in hash) {
if (Output.push (' <li><a href= ' javascript:void (0) "class=" Search_target "data-value=" ' +prefix +
prop+ ' > ' + input + "<b>" + (prefix + prop). Slice (prefix.length) + "</b></a></li>") = = 10) {
Break
}
}
}
$ ("#suggest_list"). HTML (Output.join (""));
if (!input) {//Reset All
hash = window;
Fixie = prefix = output = [];
}
});
});

When the list of prompts comes out, we monitor the upside down effect. That is, when you click on the location key of the keyboard, the entry is highlighted up and down, and it is filled in the search box. Then you need to bind the KeyUp event, check its keycode, the standard browser which it, you can see my blog post "JavaScript keyboard event summary." The realization principle is very simple, defines a peripheral variable, use to store the highlighted position (index value), then subtract one on the flip, add one at the bottom, then get all a tags in the hint list, navigate to a label with the index value, highlight it, and then remove the previously highlighted a label.
Copy Code code as follows:

by Masaki
$.require ("Ready,event,attr", function () {
var search = $ ("#search"), hash = window, prefix = "";
Search.input (function () {//Listener input
//.....
});
var glowindex =-1;
$ (document). KeyUp (function (e) {//monitor up and down
if (/search_target/i.test (e.target.classname)) {//Agent specific element only, improve performance
var Upordown = 0
if (E.which = = = E.which = =) {//up 8
Upordown--;
}else if (E.which = = | | e.which = = =//down 2
Upordown + +;
}
if (Upordown) {
var list = $ ("#suggest_list a");
Shift the highlighted columns
List.eq (Glowindex). Removeclass ("Glow_suggest");
Glowindex + = Upordown;
var el = List.eq (Glowindex). addclass ("Glow_suggest");
Fixie = el.attr ("Data-value")
Search.val (Fixie)
if (Glowindex = = list.length-1) {
Glowindex =-1;
}
}
}
});
});

Finally, carriage return is submitted. I wrote another KeyUp incident. Of course you can try to synthesize two KeyUp (monitor window), which I write purely for the purpose of teaching.
Copy Code code as follows:

by Masaki
$.require ("Ready,event,attr", function () {
var search = $ ("#search"), hash = window, prefix = "";
Search.input (function () {//Listener input
//.....
});
var glowindex =-1;
$ (window). KeyUp (function (e) {//monitor up and down
//.....
});
Search.keyup (function (e) {//Listener submit
var input = This.value;
if (input && (E.which = | | e.which = 108)) {//If the ENTER key is pressed
alert (Input)//actual project, should be the page jump, run to the search results page!
}
});
});

By this, the suggest effect is complete. If the students under my framework, turn on the server, open the document page can see this effect. And in the actual project, suggest actually simpler, is when the input box text changes, Ajax request backstage an array, and then splicing it into LI element format on the line.

Related Article

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.