Sunday, April 22, 2012

JQuery Highlight Text Plugin

jQuery.fn.highlight = function(str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function() {
        $(this).contents().filter(function() {
            return this.nodeType == 3 && regex.test(this.nodeValue);
        }).replaceWith(function() {
            return (this.nodeValue || "").replace(regex, function(match) {
                return "<span class=\"" + className + "\">" + match + "</span>";
            });
        });
    });
};

Penggunaan

Seleksi sebuah elemen kemudian terapkan fungsi .highlight("teks", "nama-kelas"):

$('p').highlight("lorem ipsum", "yellow");

Lihat Demo


Sumber: A Web Coding Blog - Highlight Words in Text with jQuery

Labels: , , ,

6 Comments:

At Monday, April 23, 2012 at 6:49:00 AM GMT+7, Blogger Sinto said...

bang kalau mau kata - kata yang di highligh lebih dari satu gimana..?

 
At Monday, April 23, 2012 at 7:21:00 AM GMT+7, Blogger Taufik Nurrohman said...

@system of blog Diurutkan saja seperti biasa:

$('p')
.highlight("in", "yellow")
.highlight("congu", "red")
.highlight("ero", "green")
.highlight("usus", "blue");


Demo: http://jsfiddle.net/tovic/kfqJu/1/

 
At Monday, April 23, 2012 at 6:31:00 PM GMT+7, Blogger Sinto said...

@Taufik Nurrohman ok deh mantap makasih

 
At Monday, April 23, 2012 at 10:57:00 PM GMT+7, Blogger Beben Koben said...

ini bagus sih, tapi kalah full stylish \o/
sama iniii
http://jsfiddle.net/codepo8/dgpzM/

kabuuurrr....

 
At Monday, April 23, 2012 at 11:14:00 PM GMT+7, Blogger Taufik Nurrohman said...

@Beben Koben Apa hubungannya? Hehe... :p :p :p

 
At Wednesday, December 4, 2013 at 5:37:00 PM GMT+7, Anonymous Anonymous said...

Karena postingan ini akhirnya bisa juga diintegrasikan sama pencarian

 

Post a Comment

<< Home