petxd086
petxd086

Reputation: 31

How to make a bookmarklet that will turn selected text into a link?

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 ?

Upvotes: 3

Views: 1269

Answers (2)

Tim Down
Tim Down

Reputation: 324737

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);
    }
})();

Upvotes: 1

wojtiku
wojtiku

Reputation: 184

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

Upvotes: 2

Related Questions