views:

22

answers:

1

What I actually want to do is get selected text when a button is pressed. It works fine in IE and Firefox with the code I am using but the selectedText variable is empty in chrome and Safari. I dont know what to do about them, any help? The code I am using is:

$('.a-button').click(function() {
    $('.bubble').hide();

    if($.browser.msie) {
        var select = window.document.selection.createRange();
        var parents = $(select.parentElement()).parents('.the-content');
    } else {
        var select = window.getSelection();
        var parents = $(select.focusNode).parents('.the-content');
    }

    var newLen = $('.new').length + 1;

    if(parents.length >= 1) {
        if($.browser.msie) {
            if($(select.parentElement()).hasClass('.an')) {
                alert('This text is already annotated.');
            } else {
                select.pasteHTML('<span class="newAnnotation" id="newAnno_'+newLen+'">' + select.htmlText + '</span>');
            }

            var selectedText = select.text;
        } else {
            if($(select.focusNode).parent().hasClass('.annotation')) {
                alert('This text is already annotated.');
            } else {
                for(var i = 0; i < select.rangeCount; i++) {
                    var range = select.getRangeAt(i); 
                    range.surroundContents($('<span class="newAnnotation" id="newAnno_'+newLen+'"></span>').get(0));
                }
            }

            var selectedText = select.toString();
        }

        alert(selectedText);

        var currentPosition = $('#newAnno_'+newLen).position();

        $('#bubble').css('position', 'absolute');
        $('#bubble').css('left', currentPosition.left);
        $('#bubble').css('top', currentPosition.top+40);

        $('#container').empty();
        $('#container').html('<img src="'+ANNOVars.pluginUrl+'/public/images/ajax-loader.gif" alt="Loading" />');

        $('#bubble').show();

        $.post(
            ANNOVars.ajaxUrl,
            {action: 'newAnnotation', postID: vars.postID, selectText: selectedText},
            function(data) {
                if(data !== 'empty') {
                    $('#container').html(data);
                    $('#bubble').show();
                } else {
                    $('#bubble').hide();
                }
            }
        );
    } else {
        alert('You cannot annotate this text.');
    }

    return false;
});
A: 

Here is the function I use in a chrome extension:

    _getSelection: function() {
            var w = window,d = document, s = '', u;

            if (w.getSelection != u) { s = w.getSelection();}
            else if (d.getSelection != u) { s = d.getSelection(); }
            else if (d.selection) { s = d.selection.createRange().text; }
            else { return ''; }

            /* other extension-related stuff.. */  

            s = String(s).trim();
            return escape(s);
    },
Jim Schubert