Skip to content Skip to sidebar Skip to footer

Javascript Window.find() Does Not Select Search Term

When I try to pass text which spreads throughout a few block elements the window.find method dosent work: HTML:

Solution 1:

JS Bin demo: http://jsbin.com/aqiciv/1/

If you want this to work in IE < 9 you'll need to add MS-specific selection code (nightmare), or use Rangy.js (pretty heavy).

functionvisibleTextNodes() {
    var walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_ALL,
        function(node) {
            if (node.nodeType == 3) {
                returnNodeFilter.FILTER_ACCEPT;
            } elseif (node.offsetWidth && node.offsetHeight && node.style.visibility != 'hidden') {
                returnNodeFilter.FILTER_SKIP;
            } else {
                returnNodeFilter.FILTER_REJECT;
            }
        },
        false
    );

    for (var nodes = []; walker.nextNode();) {
        nodes.push(walker.currentNode);
    }
    return nodes;
}

// Find the first match, select and scroll to it.// Case- and whitespace- insensitive.// For better scrolling to selection see https://gist.github.com/3744577functionhighlight(needle) {
    needle = needle.replace(/\s/g, '').toLowerCase();

    var textNodes = visibleTextNodes();

    for (var i = 0, texts = []; i < textNodes.length; i++) {
        texts.push(textNodes[i].nodeValue.replace(/\s/g, '').toLowerCase());
    }

    var matchStart = texts.join('').indexOf(needle);
    if (matchStart < 0) {
        returnfalse;
    }

    var nodeAndOffsetAtPosition = function(position) {
        for (var i = 0, consumed = 0; consumed + texts[i].length < position; i++) {
            consumed += texts[i].length;
        }
        var whitespacePrefix = textNodes[i].nodeValue.match(/^\s*/)[0];
        return [textNodes[i], position - consumed + whitespacePrefix.length];
    };

    var range = document.createRange();
    range.setStart.apply(range, nodeAndOffsetAtPosition(matchStart));
    range.setEnd.apply(  range, nodeAndOffsetAtPosition(matchStart + needle.length));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    range.startContainer.parentNode.scrollIntoView();
}

highlight('hello world');

Post a Comment for "Javascript Window.find() Does Not Select Search Term"