Question

I am using the following function to get the selected text range within a contenteditable div. This works fine in IE but not in Firefox and Chrome.

Can anyone tell me how I would need to adjust this so that it works in either both FF and Chrome or at least one of them (besides IE) ? It it would work in current versions there that would be enough. The idea with this is to replace the selected text through another function that gets the "selTxt" from here.

The function to get the selection (working in IE):

function GetSelection() 
{
selTxt = '';

if (typeof window.getSelection != "undefined") 
{
    var sel = window.getSelection();
    if (sel.rangeCount) 
    {
        var container = document.createElement('div');
        for (var i = 0, len = sel.rangeCount; i < len; ++i) 
        {
            container.appendChild(sel.getRangeAt(i).cloneContents());
        }
        selTxt = container.innerHTML;
    }
} 
else if (typeof document.selection != 'undefined') 
{
    if (document.selection.type == 'Text') 
    {
        selTxt = document.selection.createRange().htmlText;
    }
}
return selTxt;
}

The function to replace the selection (this seems to be the issue):

function EditBold()
{
    var newTxt = '';
    btnID = 'btnBold';

    GetSelection();     

    if (selTxt.toLowerCase().indexOf('<strong>') == -1)
    {
        document.selection.createRange().pasteHTML("<strong>" + selTxt + "</strong>");
    }
}

Many thanks for any help with this, Tim.

Was it helpful?

Solution

You use a variable selTxt in the EditBold() function, but don't have it declared inside the function. If the value is supposed to be what is returned by GetSelection(), use the following:

var selTxt = GetSelection();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top