views:

47

answers:

3

I'm developing a off-line web-page for iphone safari.

For highlighting the user's selection in web-page. I've implemented following code.

function highlight() {

    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }        
        document.execCommand("HiliteColor", false, "yellow");       
        document.designMode = "off";
    }
}

That's working perfectly for normal selection.

Edit :

How to detect "has user selected entire document or not ?"

What to do ?

Thanks in advance for sharing your knowledge.

Sugar.

+1  A: 

But I don't want to allow user to select entire document & highlight it.

Why not?

Interfering with users' typically-expected-browsing-experience is never a good thing and usually leads to frustrated users simply disabling JS or choosing to abandon your site altogether.

Please reconsider.

J-P
Ok ! allow - but how to detect it ?
sugar
@J-P Consider not using the word "never". There are always exceptions. The phrase "generally not" would be a far better choice here. Also, I would guess that around 95% of the web-users don't know how to turn JavaScript off.
Šime Vidas
+1  A: 

Could you use selectNodeContents(document body) (pseudocode) to create a range representing the whole page, and then compare that to the range that the user selected?

LarsH
+2  A: 

The following is a function that will return a Boolean indicating whether all of the contents of the specified element are selected and works in all major browsers, including IE. You can use this with document.body to test whether the whole page is selected.

function areElementContentsSelected(el) {
    var range, elRange;
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            elRange = document.createRange();
            elRange.selectNodeContents(el);
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                range = sel.getRangeAt(i);
                if (range.compareBoundaryPoints(range.START_TO_START, elRange) <= 0 && range.compareBoundaryPoints(range.END_TO_END, elRange) >= 0) {
                    return true;
                }
            }
        }
    } else if (document.selection && document.selection.createRange && document.selection.type == "Text") {
        range = document.selection.createRange();
        elRange = range.duplicate();
        elRange.moveToElementText(el);
        return range.compareEndPoints("StartToStart", elRange) <= 0 && range.compareEndPoints("EndToEnd", elRange) >= 0;
    }
    return false;
}

alert( areElementContentsSelected(document.body) );
Tim Down