Highlight search words like Chrome using jQuery

I recently made a very simple selection using jQuery and the main plugin. It looks like this:

$ ('myButton'). click (function () {

.

$ ('body') highlight ($ ('# myInputText') Val ().);

});

But I am wondering how I can make Chrome as a selection, I mean the selection of letters whenever I type text in a text box without sending. I think it's possible to use the keyup event ... Any ideas?

Thanks Andy, I changed 'this [0]' to 'search [i]' in your code and it works if there is only one tag 'p'

$(document).ready(function(){
  var search = ['p', 'div', 'span'];

  $("#highlighter").bind('keyup', function(e){
    var pattern = $(this).val();

    $.each(search, function(i){
        var str = search[i];        
        var orgText = $(str).text();

        orgText = orgText.replace(pattern, function($1){
          return "<span style='background-color: red;'>" + $1 + "</span>"
        });

        $(str).html(orgText);
    });    
  });
});
+5
source share
3 answers

I made it a quick exterior, code:

    $(document).ready(function(){
    var search = ['p', 'div', 'span'];

    $("#highlighter").bind('keyup', function(e){
    var pattern = $(this).val();

    $.each(search, function(i){
        var str = this[0];        
        var orgText = $(str).text();

        orgText = orgText.replace(pattern, function($1){
          return "<span style='background-color: red;'>" + $1 + "</span>"
        });

        $(str).html(orgText);
    });    
  });
});​​

: http://jsbin.com/amica3/edit

+5
$('#myInputText').keypress(function(e) {
    switch (e.keyCode) {
        case 13: // "Enter" was pressed; handle it if you want
            return false;

        case 27: // ESC was pressed; handle it if you want
            return false;
    }

    $('body').highlight($(this).val());
});
+3

I edited the JAndy code, so the result will match all occurrences in the text, and the search will not be case sensitive. Link Hope someone finds this useful

+3
source

All Articles