Home Web Front-end JS Tutorial javascript suggest effect automatic completion code sharing_javascript skills

javascript suggest effect automatic completion code sharing_javascript skills

May 16, 2016 pm 05:56 PM
automatic completion

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 < 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( '
  • ' input "" (prefix prop ).slice( prefix.length ) "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 of this Website
    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

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

    Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

    Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

    JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

    Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

    There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

    Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

    Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

    How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

    Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

    How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

    How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

    The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

    The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

    The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

    In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

    See all articles