views:

79

answers:

1

Hello,

First StackOverflow question - woo!

Quick question about styling this piece of Javascript:

    //Search
$('#search').keydown(function(e) {
    setTimeout(function() {
        if ($('#search').val() == '') {
            $('#history h4').show();
            $('#history li li').show();
            return;
        }

        $('#history h4').hide();

        var search = $('#search').val().toLowerCase();

        $('#history li li').each(function() {
            var thisId = $(this).attr('id').substr(13);
            var item = $.grep(history, function(item) { return item.id == thisId; })[0];
            if (item.message.toLowerCase().indexOf(search) != -1 || item.link.toLowerCase().indexOf(search) != -1)
                $(this).show();
            else
                $(this).hide();
        });
    }, 1);
});
});

Where do I put the CSS styling in the javascript to highlight the letters in the search results?

<font class="highlight"></font>

This is similar to searching using Ctrl+F in the browser.

Any help would be greatly appreciate. Thanks!

JP

+2  A: 

In your second if statement you could add something like:

reg_expression = new RegExp("(" + search + ")","ig");
$(this).html($(this).html().replace(reg_expression, '<span class="highlight">' + "$1" + '</span>'));

Note that I´ve used span instead of font for the highlight class.

Also note that I am assuming that your li li only contains texts and no html tags because any sequence of characters matching search will be replaced by <span>search</span> so that could lead to trouble if you have for example links where the href value contains your search term.

By the way, you need to remove all span's or fonts's before you add the new ones.

jeroen
Hi Jeroen, thank you very much for your help! The search results do contain html tags - so when I implement it, it returns very messy. Any idea to keep the formatting intact?
jprim
In that case I guess you will have to loop through all elements in `$(this)` and exclude html tags. Something like that...
jeroen