Search code examples
jqueryappendright-clickselectedtext

Append something to selected text with jquery


I'm trying to append an <a> tag in to selected text when user right click on it.i searched over the stack , no matches found.


Solution

  • Dealing with selected text reliably is a bit tricky cross-browser. Tim Down's library Rangy can be useful there, he's smoothed over a lot of the browser idiosyncrasies. (Even if you don't want to use the library, you can study it for the techniques.)

    One of the core Rangy demos is surrounding selected text with an element, using the RangyRange#surroundContents method. The code for that in the demo looks like this:

    function getFirstRange() {
        var sel = rangy.getSelection();
        return sel.rangeCount ? sel.getRangeAt(0) : null;
    }
    function surroundRange() {
        var range = getFirstRange();
        if (range) {
            var el = document.createElement("span");
            el.style.backgroundColor = "pink";
            try {
                range.surroundContents(el);
            } catch(ex) {
                if ((ex instanceof rangy.RangeException || Object.prototype.toString.call(ex) == "[object RangeException]") && ex.code == 1) {
                    alert("Unable to surround range because range partially selects a non-text node. See DOM Level 2 Range spec for more information.\n\n" + ex);
                } else {
                    alert("Unexpected errror: " + ex);
                }
            }
        }
    }
    

    You'd be doing much the same, but with an a rather than a span.