search
HomeWeb Front-endJS Tutorialjavascript suggest effect automatic completion code sharing_javascript skills

First of all, the framework used is of course my framework mass Framework. Of course, you can also use other frameworks, such as jQuery. There is nothing complicated. As long as you understand the principle, you can do it in no time. Presumably, you will also encounter the task of building a search box in your future work.

Since I don’t have a backend, I use an object as a local database. What I want to do now is actually far more advanced than suggestion, something similar to the syntax prompts of an IDE. The current finished product has been put on github.

javascript suggest effect automatic completion code sharing_javascript skills

Okay, let’s do it. The first is the structural layer. Students who have installed FF can view the source code on the Baidu homepage. When a few letters are entered, the HTML will be dynamically generated. But no matter what, the result is that a DIV is placed below the search bar, with a table inside, and the table dynamically stores candidate words. And if the candidate words are not part of the user input, that is, the parts automatically added by JS, it will put them in a b tag and display them in bold. However, I felt that using table was too heavy-duty, so I used a ul list instead. In order to make IE6 also support the skimming color effect, I also put an a tag in it. In order to make it easier to pick words, I also added an attribute to it (a tag), which is specially used to store the vocabulary after the completion. It probably looks like this:

Copy code The code is as follows:

Look at the structure. It is actually two parts. div#search_wrapper is visible and div#suggest_wrapper is "invisible" (as long as there is no li element in it, it does not take up space and cannot be displayed). The input search box has an attribute autocomplete, which is used to turn off the prompt function that comes with the browser. Regarding data-value, this naming method is recommended by HTML5 and is used to define the data to be cached. Data-* will be placed in an object called dataset in cutting-edge browsers. For example:
Copy code The code is as follows:

data-drink="coffee"
data-meal-time="12:00">12:00


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

var el= document.getElementById('Situ Zhengmei') ;
alert( el.dataset.drink );
alert( el.dataset.mealTime );

Of course, you can also directly take the innerText or textContext.
Note: Complete vocabulary = user input part auto-suggestion part. Therefore, you should not add so many things in the a tag to prevent spaces or other things from appearing, causing the retrieval to fail!
Then there is the style part, but I won’t go into details. Very simple:
Copy code The code is 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, let’s get to the point. Since I don't have a backend, I want to use a local object as a local database. This object is of course a JS object. The objects we traverse are usually obj.aaa.bbb.ccc. If we keep clicking in this way, in fact, every time we reach a dot number, we use a for in loop to traverse. Therefore, we monitor the input of text content, obtain the content of the input box once it changes, and then compare it in the for in loop. If it is an attribute that starts with this input value, take it out and put it into an array until you get ten. Then splice the contents of these arrays into the li element format depicted above and paste them into the ul element. Among them, we also need to pay attention to the dots. If we enter the dot number at the beginning, we will take the ten attributes of the window object. When we encounter the dot number in the future, we will switch this object.
Okay, let’s start writing code. Since my framework is used, you can go here. There is a README on the project homepage, which teaches you how to install the micro.Net server and view documents. At the beginning, you can think of it as jQuery with the module loading function added. The API is 90% similar. We need to use its event module and attribute module. It will load the relevant dependencies, add the ready parameter, and it will be executed after domReady. After we select the input box, we bind an input event to it. This is an event supported by standard browsers. My framework is already compatible under IE. Students who use jQuery and native please use the propertychange event to simulate it.
Copy code The code is as follows:

//by Situ Zhengmei
$.require( "ready,event,attr",function(){
var search = $("#search"), hash = window, prefix = "", fixIE = NaN;
search.addClass("search_target") ;
search.input(function(){//Monitor input
var
input = this.value,//Original value
val = input.slice( prefix.length),//Compare Value
output = []; //Used to place the output content
if( fixIE === input){
return //IE fix will be triggered even if the value in the input box is changed through the program The propertychange event prevents us from flipping up and down
}
for(var prop in hash){
if( prop.indexOf( val ) === 0 ){//Get the index starting with the input value API
if( output.push( '
  • ' input " " (prefix prop ).slice( input.length ) "
  • " ) == 10){
    break;
    }
    }
    }
    //If a dot is encountered forward, or a dot is canceled backwards
    if( val.charAt(val.length - 1) === "." || (input && !val) ){
    var arr = input.split("."); hash = window;
    for(var j = 0; 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( '
  • ' input "" (prefix prop ).slice( prefix.length ) "
  • > ;" ) == 10){
    break;
    }
    }
    }
    $("#suggest_list").html( output.join("") );
    if(!input){//Reset all
    hash = window;
    fixIE = prefix = output = [];
    }
    });
    });

    When the prompt list comes out, we monitor the up and down effect. That is, when you click the direction key on the keyboard, the prompted item will be highlighted up and down, and it will be filled in the search box. At this time, you need to bind the keyup event and check its keyCode. Standard browsers call it which. You can read my blog post "Javascript Keyboard Event Summary". The implementation principle is very simple. Define a peripheral variable to store the highlighted position (index value), then decrease it by one when scrolling up, and increase it by one when scrolling down. Then get all a tags in the prompt list. Use the index value to locate a certain a tag, highlight it, and then remove the originally highlighted a tag.
    Copy code The code is as follows:

    //by Situ Zhengmei
    $.require("ready,event,attr",function(){
    var search = $("#search"), hash = window, prefix = "";
    search.input(function(){//Monitor input
    //.....
    });
    var glowIndex = -1;
    $(document) .keyup(function(e){//Monitor up and down
    if(/search_target/i.test( e.target.className)){//Only proxy specific elements to improve performance
    var upOrdown = 0
    if(e.which === 38 || e.which === 104){ //up 8
    upOrdown --;
    }else if(e.which === 40 || e .which === 98){//down 2
    upOrdown ;
    }
    if(upOrdown){
    var list = $("#suggest_list a");
    //Transfer Highlighted column
    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, press Enter to submit. I wrote another keyup event. Of course, you can try to combine two keyups into one (monitoring window). I wrote it this way purely for teaching purposes.
    Copy code The code is as follows:

    //by Situ Zhengmei
    $.require( "ready,event,attr",function(){
    var search = $("#search"), hash = window, prefix = "";
    search.input(function(){//Listen to input
    //.....
    });
    var glowIndex = -1;
    $(window).keyup(function(e){//Listen for up and down scrolling
    // .....
    });
    search.keyup(function(e){//Listen for submission
    var input = this.value;
    if(input && (e.which == 13 || e.which == 108)){ //If you press the ENTER key
    alert(input)//In the actual project, the page should jump and go to the search results page }
    });
    });

    At this point, the suggestion effect is completed. If you have downloaded my framework, you can see this effect by turning on the server and opening the document homepage. In actual projects, suggestion is actually simpler. When the input box text changes, AJAX requests an array in the background, and then splices it into the format of the li element.
    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

    Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

    Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

    Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

    Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

    The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

    The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

    JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.