MozillaZine

Creating Links with Mozilla's window.getSelection() Method

Friday October 25th, 2002

Kenneth Dillon writes: "This morning, IBM developerWorks published a tutorial detailing how Mozilla's cutting-edge ECMAScript and W3C DOM support and its nonstandard, but incredibly useful window.getSelection() method can be put to work to allow users to create links to virtually any piece of text within an HTML document."

Note that you must have a developerWorks profile to access this tutorial. You can create a free profile at the registration page.


#14 A not so simple example.

by ipottinger

Saturday October 26th, 2002 3:31 PM

You are replying to this message

The following bookmark is a modification of Jesse Ruderman's "highlight" bookmarket found at <http://www.squarefree.com…s/pagedata.html#highlight> . Copy and paste it to a new bookmark and specify a keyword. (I suggest keyword "highlight" with no quotes)

It can be activated in 4 ways:

1) enter the keyword alone ("highlight") into the url bar. It will prompt you for a word in the current page to highlight.

2) enter the keyword followed by phrase ("highlight simple example") into the url bar.

3) select this bookmark from the bookmark menu/personal toolbar/sidebar. It will prompt you for a word in the current page to highlight.

4) highlight some text on the current page and select this bookmark from the bookmark menu/personal toolbar/sidebar.

---begin cut below ---

javascript:(function(){var count=0, text, dv;text="%s";alert("text >"+text+"<\nlen(text)="+text.length);if(text=="%s"){text=document.getSelection();}if(text==null || text.length==0){text=prompt("Highlight phrase:", "");}if(text==null || text.length==0)return;dv=document.defaultView;function searchWithinNode(node, te, len){var pos, skip, spannode, middlebit, endbit, middleclone;skip=0;if( node.nodeType==3 ){pos=node.data.toUpperCase().indexOf(te);if(pos>=0){spannode=document.createElement("SPAN");spannode.style.backgroundColor="yellow";middlebit=node.splitText(pos);endbit=middlebit.splitText(len);middleclone=middlebit.cloneNode(true);spannode.appendChild(middleclone);middlebit.parentNode.replaceChild(spannode,middlebit);++count;skip=1;}}else if( node.nodeType==1&& node.childNodes&& dv.getComputedStyle(node, null).getPropertyValue("display")!="none"){for (var child=0; child < node.childNodes.length; ++child){child=child+searchWithinNode(node.childNodes[child], te, len);}}return skip;}window.status="Searching for '"+text+"'...";searchWithinNode(document.body, text.toUpperCase(), text.length);window.status="Found "+count+" occurrence"+(count==1?"":"s")+" of '"+text+"'.";})();

--- end cut above ---