3

Let's say you

  1. select "some text" an browser.
  2. Click a bookmarklet
  3. the selected text turns into simple link with the url of the current page.

How should I implement this ?

2

Sample code tested in Firefox 3.6, Chome 6 and Opera 10.6 which does exactly what you described in your question.

javascript:(
    function(){
        var range = window.getSelection().getRangeAt(0);
        var a = document.createElement('a');
        a.setAttribute('href',document.location);
        a.appendChild(document.createTextNode(window.getSelection().toString()));
        range.deleteContents();
        range.insertNode(a);
    }
)()

If you need it to be compatible with IE read this post: http://www.daniweb.com/forums/thread85642.html

1

The following is very similar to @wojtiku's answer but adds IE support and a few extra checks and improvements:

javascript:(function() {
    var sel, range, a;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            a = document.createElement("a");
            a.href = window.location.href;
            a.appendChild(document.createTextNode("" + sel));
            range.deleteContents();
            range.insertNode(a);
        }
    } else if (document.selection && document.selection.type == "Text") {
        range = document.selection.createRange();
        a = document.createElement("a");
        a.href = window.location.href;
        a.appendChild(document.createTextNode(range.text));
        range.pasteHTML(a.outerHTML);
    }
})();
  • Thanks. That's wonderful ! I hope you understand what one can do with this bookmarklet. Simply create a link out of piece of text and drag to bookmarks toolbar. You'll gett a bookmark which displays selected text. No more silly Scrapbooks in firefox or Opera Notes in Opera. Just store all your notes as bookmarks in the same tree. What can be more handy ? Thanks again, guys. – petxd086 Nov 8 '10 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.