jQuery & Wordpress Live AJax Search

GitHub

Use this plug-in on a search form, and the search results will update as the user types.

You can add the search results element anywhere on the page you want, but the plug-in comes with some default CSS for displaying it directly beneath the input field.

The plug-in itself will not handle the actual search, instead you tell it which page to load as the user types. This page will be the one responsible for displaying the search results.

If you're using WordPress, you'll set this URL: "/?s=" and the plug-in will fire off an AJAX request to /?s=[whatever the user typed] and display the results in the box.

Here's how you use it:

<form method="get" action="/" id="live-search-example">
    <div><input type="text" name="s" placeholder="Search"></div>
</form>

<script>
    LiveSearch.init(document.getElementById('live-search-example').querySelector('input[name=s]'), {url: '/?s='}});
</script>

Or if you're using jQuery you can go $('#live-search-example input[name=s]').liveSearch({url: '/?s='});.

If you do implement this on WordPress, you need to make sure your search.php-template doesn't return the entire page on AJAX requests, something like this:

<!-- Only display a list of results on ajax requests - no <head> etc -->
<?php if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') : ?>
    <?php if (have_posts()) : ?>
        <ul>
            <?php while (have_posts()) : the_post() ?>
                <li>
                    <a href="<?php the_permalink() ?>">
                        <?php the_post_thumbnail() ?> 
                        <?php the_title() ?>
                    </a>
                </li>
            <?php endwhile ?>
        </ul>
    <?php else : ?>
        <p>No results :(</p>
    <?php endif ?>
<!-- Normal search results code -->
<?php else : ?>
    <?php get_header() ?>
    etc...
<?php endif ?>

This version of the plug-in only takes care of populating the search results. CSS is used for all animations and showing hiding. Only an :empty search results box will be hidden, so it no longer is enough to just un-focus the input. You could do this with CSS, but the result is that you can't click anywhere inside the box :/

You'll find the CSS here and the JS here.

Download on GitHub