文字列をリアルタイム検索してハイライトする

Ads

Result

jQuery

// by Real-Time Search in JavaScript
//http://osvaldas.info/real-time-search-in-javascript

'use strict';

(function ($, window, document, undefined) {
    var $container = $('.faq');
    if (!$container.length) return true;

    var $input = $container.find('input'),
        $notfound = $container.find('.faq__notfound'),
        $items = $container.find('> ul > li'),
        $item = $(),
        itemsIndexed = [];

    $items.each(function () {
//正規表現でキーワードを抽出
        itemsIndexed.push($(this).text().replace(/\s{2,}/g, ' ').toLowerCase());
    });

    $input.on('keyup', function (e) {
        if (e.keyCode == 13) // enter
        {
            $input.trigger('blur');
            return true;
        }

        $items.each(function () {
            $item = $(this);
//spanで括ってハイライト
            $item.html($item.html().replace(/<span class="highlight">([^<]+)<\/span>/gi, '$1'));
        });

        var searchVal = $.trim($input.val()).toLowerCase();
        if (searchVal.length) {
            for (var i in itemsIndexed) {
                $item = $items.eq(i);
                if (itemsIndexed[i].indexOf(searchVal) != -1) $item.removeClass('is-hidden').html($item.html().replace(new RegExp(searchVal + '(?!([^<]+)?>)', 'gi'), '<span class="highlight">$&</span>'));
                else $item.addClass('is-hidden');
            }
        } else $items.removeClass('is-hidden');

        $notfound.toggleClass('is-visible', $items.not('.is-hidden').length == 0);
    });
})(jQuery, window, document);

css

.faq .highlight {
	background-color: #fffd77;
}
.faq > ul > li.is-hidden {
	display: none;
}
.faq__notfound {
	font-size: 20px;
	display: none;
}

html

<div class="faq">
        <input type="search" value="" placeholder="検索するキーワード" />
        <ul>
            <li id="faq-1">
                	<h2>foo</h2>

                <div>
                    <p>bar</p>
                </div>
            </li>
            <li id="faq-2">
                	<h2>hoge</h2>

                <div>
                    <p>huga</p>
                </div>
            </li>
            <li id="faq-3">
                	<h2>piyo</h2>

                <div>
                    <p>piyopiyo</p>
                </div>
            </li>
        </ul>
        <div class="faq__notfound">
            <p>キーワードが見当たりません。他のキーワードをお試し下さい</p>
        </div>
    </div>

via

Real-Time Search in JavaScript by Osvaldas Valutis.

タイトルとURLをコピーしました