Reputation: 31
Let's say you
How should I implement this ?
Upvotes: 3
Views: 1269
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
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