Cross Browser Selection Range Library?

Does anyone know of any cross-browser user selection range libraries written in javascript?

I found a few jQuery plugins, (which quite frankly are too limiting and very buggy).

I would just like to know what you have found out there. Don't send me googling this again, (I've spent days working on all this). Hopefully, this can be where future programmers can find the answer.

Answers:

Answer

I've developed a cross-browser Range and selection library called Rangy. Its core is not dissimilar in concept to IERange but goes beyond it in terms of implementation of the DOM level 2 Range and HTML5 selection specifications, and also in terms of stability and workarounds for browser bugs. I think it's the best there is out there.

There are also extra modules for saving, restoring and serializing selections and applying CSS class to ranges and selections.

https://github.com/timdown/rangy

The following uses some Rangy extensions to Ranges to easily iterate over text nodes within a selection and surround each one:

function surroundSelectedText(templateElement){
    var range, sel = rangy.getSelection();
    var ranges = sel.getAllRanges();
    var textNodes, textNode, el, i, len, j, jLen;
    for (i = 0, len = ranges.length; i < len; ++i) {
        range = ranges[i];
        // If one or both of the range boundaries falls in the middle
        // of a text node, the following line splits the text node at the
        // boundary
        range.splitBoundaries();

        // The first parameter below is an array of valid nodeTypes
        // (in this case, text nodes only)
        textNodes = range.getNodes([3]);

        for (j = 0, jLen = textNodes.length; j < jLen; ++j) {
            textNode = textNodes[j];
            el = templateElement.cloneNode(false);
            textNode.parentNode.insertBefore(el, textNode);
            el.appendChild(textNode);
        }
    }
}

var span = document.createElement("span");
span.style.color = "green";
span.style.fontWeight = "bold";

surroundSelectedText(span);
Answer

For the jQuery plugin option there's jCaret, you can check out the homepage here and the examples here.

I've used this on a few projects for various applications, works well at removing the cross-browser inconsistencies.

Answer

For general-purpose range work (as opposed to input/textarea selection handling), consider ierange. Attempts to implement the standard DOM Level 2 Range model supported by other browsers in IE. Kind-of works.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.