Hello.
I have this JS code which I found on the web. It searches for a text string the user inserts into a textfield. I would like to be able to tap a button that goes either to next or previous occurrence. Setting up the GUI is not a problem, it's just how to code the next/previous function in JS. (I'm developing for iOS using a UIWebView, but that shouldn't be an issue here, since the code revolves around JS):
I have this JS code which I found on the web. It searches for a text string the user inserts into a textfield. I would like to be able to tap a button that goes either to next or previous occurrence. Setting up the GUI is not a problem, it's just how to code the next/previous function in JS. (I'm developing for iOS using a UIWebView, but that shouldn't be an issue here, since the code revolves around JS):
Code:
function HighlightAllOccurencesOfStringForElement(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);
span.setAttribute("class","MyAppHighlight");
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;
span.scrollIntoView(); // THIS SCROLLS TO THE FIRST SEARCH OCCURRENCE
span.style.backgroundColor="yellow"; // must set the CSS style after scrolling to first search instance
span.style.color="black";
SearchResultCount++; // update the counter
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}