Skip to content Skip to sidebar Skip to footer

Prevent JavaScript Window.getSelection() Circular Reference

See this demo (dependent on selectionchange event which works in Chrome only at this moment): http://jsfiddle.net/fyG3H/ Select some lorem ipsum text and then focus the text input.

Solution 1:

You need to invoke toString() on getSelection(). I've updated your fiddle to behave as you'd expect.

var selection;

$('p').bind('mouseup', function() {
    selection = window.getSelection().toString();
});

$('input').bind('focus', function() {
   this.value = selection;
   console.log(selection); 
});

See demo


EDIT:

The reason that you're not getting the correct anchor node is that the DOMSelection object is passed by reference and when you focus on the input, the selection gets cleared, thus returning the selection defaults corresponding to no selection. One way you can get around this is to clone the DOMSelection properties to an object and reference that. You won't have the prototypal DOMSelection methods any more, but depending on what you want to do this may be sufficient.

var selection, clone;

$('p').bind('mouseup', function() {
    selection = window.getSelection();
    clone = {};
    for (var p in selection) {
        if (selection.hasOwnProperty(p)) {
            clone[p] = selection[p];
        }
    }
});

$('input').bind('focus', function() {
   console.dir(clone); 
});

See demo


Post a Comment for "Prevent JavaScript Window.getSelection() Circular Reference"