praveenpds praveenpds - 1 month ago 14
jQuery Question

High light the searched text using AngularJS , jQuery and Css

Im using this jquery plugin for searching text :"http://code.google.com/p/jquery-highlight/downloads/list "..

But im not able to wrap this code in AngularJS,
I mean to say "i'm unable to write a directive to call this jquery plug in"...!!!

Updated :

Same post in Google group:

This is the group

Answer Source

UPDATE: This is just an example. You can modify as per your needs.

You don't need RegExp comparison for that. Lets make simple use of javascript's split() function

1) Define a style for highlighting.

.srchslctn{
    background-color: yellowgreen;
    color: red;
}

2) Your sample HTML

<body>
    <div>
        <div id="serach-Paragraph">
            Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
        </div>
        <input type="button" id="h" value="Highlight"/>
        <div id="target"></div>
    </div>
</body>

3) JavaScript

            $(document).ready(function(){
            $("#h").on('click',function(){
                highlight(); 
            });
        });

        function highlight(){
            $("#target").empty();
            var mainString = $("#serach-Paragraph").html();
            var searchString = "ipsum";
            var arr = mainString.split(searchString);
            var len = arr.length;
            var finalString="";
            for(var i=0;i<arr.length;i++){

                finalString+=arr[i];

                if(i<len-1){
                    finalString+='<span class="srchslctn">'+searchString+'</span>';
                }
            }
            $("#target").html(finalString);
        }

Thats it....

Explanation -: split() will break the targetString according to your searchString. This is similar to how we retrieve comma separated values. Only thing is in this case your search string acts like comma :)

Then keep arr[0] as it is. Highlight your search string and append it to arr[0]. Append arr[1] to above result and so on.

Simple....


Searched text as in you have to only highlight the matched part keeping rest of the text as it is?