Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting search words like Chrome with jQuery

I have recently done a very simple highlighting with jQuery and a highlight plugin. It looks like this:

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

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

});

But I wonder how can I do the Chrome like highlighting, I mean highlight the letters whenever I type in some letter in textbox without submitting. I think maybe use a keyup event... Any ideas?

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

$(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);
    });    
  });
});
like image 330
ilkin Avatar asked Mar 31 '10 07:03

ilkin


People also ask

How do I highlight text in Javascript search?

js code to highlight the text. There are many built-in functions in mark. js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before.

How do I highlight certain words in my browser?

Simply navigate to a web page, then, open toolbar popup UI and type your keyword in the designated area. Then click on the "Find" button or press "Enter" on your keyboard. All the matching words within the web page will be highlighted with yellow color.


2 Answers

I made quick excersise out of it, 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);
    });    
  });
});​​

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

like image 149
jAndy Avatar answered Oct 11 '22 18:10

jAndy


$('#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());
});
like image 33
Thomas Bonini Avatar answered Oct 11 '22 17:10

Thomas Bonini