Realtime Search 2
by mattography
HTML
<input type="text" id="input" name="input" />
<div id="content-block">
<p>lorem ip sum</p>
</div>
CSS
.highlight {
background-color:blue
}
JavaScript
$('#input').live('keyup', function () {
$('#input').trigger('highLight');
});
$('#input').bind('highLight', function () {
var o = {
words: $('input[name="input"]').val()
};
highlight("content-block", o);
});
function highlight(id, options) {
var o = {
words: '',
caseSensitive: false,
wordsOnly: true,
template: '$1<span class="highlight">$2</span>$3'
},
pattern;
$.extend(true, o, options || {});
if (o.words.length == 0) {
return;
}
pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");
$('#' + id).each(function () {
$('span.highlight', this).replaceWith($('span.highlight', this).text()); // Fix
var content = $(this).html();
if (!content) return;
$(this).html(content.replace(pattern, o.template));
});
}