0 works

Live Search Bar on Website


dashboard+ Project

Posted by @mishka #javascript

Code snippet:

(function(){
    //
    var $posts = $('#posts li');
    var $search = $('#search');
    var cache = [];

    $posts.each(function(){
        cache.push({
            element: this,
            title: this.title.trim().toLowerCase(),
        });
    });

    function filter(){
        var query = this.value;
        console.log("query is "+query);
        cache.forEach(function(post){
            var index = 0;

            if (query) {
                index = post.title.indexOf(query);

            }
            var results = document.getElementsByClassName('search-results');
            results.innerHTML = "<li>"+cache.title+"</li>";
            post.element.style.display = index === -1 ? 'none' : '';
        });
    }

   if ('oninput' in $search[0]){
        $search.on('input', filter);
    } else {
        $search.on('keyup', filter);
    }

}());
content_copyCopy to Clipboard

More details:

Make sure you have jquery installed. If the code interferes with other functions then remove the oninput function and use only $search.on('keyup', filter);

Code snippet source:

https://www.amazon.com/JavaScript-JQuery-Interactive-Front-End-Development/dp/1118531647

>> Browse more code snippets

more_vert