Wednesday 1 February 2017

javascript - search highlight, next, previous functionality for mobile, web,UIWebView, html - Code

The Searching text in html DOM using JavaScript, like html but its not html as it is in mobile application WebView /UIWebView. well its not too tough. Recently I helped one of my closest friend in her Mobile Application, She wants to give functionality to Search any of text and highlight all texts, as well as give option to navigate next and previous searched string by tapping on tables screen.
She got some code from internet, but that was just to search text that too in reverse / random order (as used recursion). I just help her to fex the issue by adding Nxt, Prv, SetStatusText, SetSequencing etc.

below is thee code here, you can click here to see the Demo.


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
<!DOCTYPE>
<html>
<script type="text/javascript" >

var totalsearchResultsFoundCount = 0;
var currentCount = -1;
var defaultSelectionColor = "#87CEFA";
var selectedSelectionColor = "#FFDEAD";
var keyNameHighlight = "IdhighlightMe";
var NxtHitCount = -1;

var nxtPrvColor = "red";
var arraySequenceId = 0;
var objSearchItems =  {};

function setStatusText(){
    var sts = document.getElementById("statusText");
    if(totalsearchResultsFoundCount>0)
    sts.innerHTML = (arraySequenceId+1)+ " of "+totalsearchResultsFoundCount;   
    else sts.innerHTML = "";
}

function SetSequencing(){
   
    var x = document.getElementsByClassName(keyNameHighlight);   
    for(var i = 0; i < x.length; i++){  
        for(var seq = 0; seq < objSearchItems.length; seq++){
            if(objSearchItems[seq].id == x[i].id){               
                objSearchItems[seq].ActualSequenceNumber = i;
                console.log(objSearchItems[seq].id + " " + x[i].id + " updated "+ objSearchItems[seq].ActualSequenceNumber);
            }
        }       
    }
}

function GetIdAndHighlight(){
    var span = document.getElementById(keyNameHighlight+"0");
    for(var seq = 0; seq < objSearchItems.length; seq++){
        var span = document.getElementById(objSearchItems[seq].id);
        if(objSearchItems[seq].ActualSequenceNumber == arraySequenceId)
        {
            span.style.backgroundColor = nxtPrvColor;
        }
        else{
            span.style.backgroundColor = defaultSelectionColor;       
        }
    }
    return span;
}

function Prv() {
   
    if(arraySequenceId <= 0){
        arraySequenceId = (totalsearchResultsFoundCount-1);
    }
    else if (arraySequenceId > 0) {
          --arraySequenceId;         
    }
    GetIdAndHighlight();
    setStatusText();
    //scrollView();
}

function Nxt(){   
    if(arraySequenceId < (totalsearchResultsFoundCount-1)){
        ++arraySequenceId ;
    }
    else if(arraySequenceId >= (totalsearchResultsFoundCount-1)){
        arraySequenceId = 0;
    }
    GetIdAndHighlight();setStatusText();
    //scrollView();
}

// helper function, recursively searches in elements and their child nodes
function GetAllOccurencesOfTextForElement(element,keyword) {
    if (element) {
        if (element.nodeType == 3) {        // Text node
            while (true) {
                var value = element.nodeValue;  // Search for keyword in text node
              
                var idx = value.toLowerCase().indexOf(keyword);
                if (idx < 0) break;             // not found, abort
              
                var span = document.createElement("span");
                var text = document.createTextNode(value.substr(idx,keyword.length));
                span.appendChild(text);
                var str1 = keyNameHighlight+totalsearchResultsFoundCount;
                span.setAttribute("class", keyNameHighlight);
                span.setAttribute("id", str1);
                span.style.backgroundColor = defaultSelectionColor;
                span.style.color = "black";
                text = document.createTextNode(value.substr(idx+keyword.length));
                element.deleteData(idx, value.length - idx);
                var next = element.nextSibling;
                element.parentNode.insertBefore(span, next);
                element.parentNode.insertBefore(text, next);
                element = text;
                totalsearchResultsFoundCount++;  // update the counter
               
                objSearchItems.push({id:str1,IsSelected:false,searchResultSerial:totalsearchResultsFoundCount,ActualSequenceNumber:-1});               
                //console.log(objSearchItems);
            }
        } else if (element.nodeType == 1) { // // Element node - Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
            if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
              
                for (var currentElement = element.childNodes.length-1; currentElement >= 0; currentElement--) {
                    GetAllOccurencesOfTextForElement(element.childNodes[currentElement],keyword);
                }
            }
        }
    }
}

function GetAllOccurencesOfText(keyword) {
  
    removeExistingHighlights();
   
    keyword = document.getElementById('txt').value ;
   
    objSearchItems = new Array();
   
    GetAllOccurencesOfTextForElement(document.body, keyword.toLowerCase());
   
    SetSequencing();
   
    GetIdAndHighlight();
   
    setStatusText();
       
}

// helper function, recursively removes the highlights in elements and their childs
function removeExistingHighlightsForElement(element) {
    if (element) {
        if (element.nodeType == 1) {
            if (element.getAttribute("class") == keyNameHighlight) {
                var text = element.removeChild(element.firstChild);
                element.parentNode.insertBefore(text,element);
                element.parentNode.removeChild(element);
                return true;
            } else {
                var normalize = false;
                for (var currentElement = element.childNodes.length-1; currentElement >= 0; currentElement--) {
                    if (removeExistingHighlightsForElement(element.childNodes[currentElement])) {
                        normalize = true;
                    }
                }
                if (normalize) {
                    element.normalize();
                }
            }
        }
    }
    return false;
}

// the main entry point to remove the highlights
function removeExistingHighlights() {
    totalsearchResultsFoundCount = 0;
    currentCount = -1;
    arraySequenceId = 0;
    removeExistingHighlightsForElement(document.body);
}

function scrollView() {
     
}  

</script>
<body>

<article type="article" id="v9s28660" language="eng-EN">
   <title>
      Search - Praveen Text
   </title>
   <text>

         <p class="lvl-01"> 

Microsoft Certified Professional Developer (MCPD 100%)Praveen 
SharePoint Online /Office 365 /SharePoint 2013 / SharePoint 2010
SOM, CSOM ,REST, SPSservices, Praveen Events, Custom timer jobs, custom webparts, OOB webpart, Client object model (JS/C#), Designer, Infopath, BCS and Search, PowerShell ,Deployment , installation configuration, C#, ASP.NET, JavaScript, CSS, HTML,JQuery and Angular JS.
Actively involved and have lead end  Praveen to end project life cycle, Requirement understanding, Designing, Effort estimation, project delivery, Sing offs and team management. hands-on, C#, C, HTML, JavaScript, invoice in JAVA, MySql, DBMS. Always interested in new innovative idea and to learn new technologies, as well keeps close interaction about developing new applications in SharePoint

and some more Praveen text
Notifications have always been a key use case for Pebble, and we are excited by this
 new feature which is going to change the way you look at notifications. With 
actionable Praveen notifications Pebble not only informs you about relevant events, users
 can now interact with them and choose Praveen from actions you as an Android developer 
attach to them


</p>     
   </text>
</article>  
    <input type='text' id='txt' value='Praveen' />
    <br><br>
    <input type=button onclick='GetAllOccurencesOfText();' value='Search'>;
    <input type=button onclick='Prv();' value='P-Prv'>;
    <input type=button onclick='Nxt();' value='P-Nxt'>;
    <span id='statusText'/>
</body>

</html>


--
Comments & Feedback are welcome, and yeah don't forget to share this make short link.

No comments:

Post a Comment