Search code examples
jquerybackbone.js

backbone view and window.getSelection


I'm having trouble getting window.getSelection to work inside a backbone.js view.

The view works fine otherwise, but whenever I select some text, then click on my test button that triggers the window.getSelection function, the selection always shows as empty.

I figure it may have something to do with my view and the way views attach to the page.

Here is my test code:

return Backbone.View.extend({

    tagName: 'div',
    className: 'test',
    template: _.template(tmpl, null, { }),

    events: {
        "click .testSelection": "testSelection"
    },

    initialize: {...}
    render: {...}

    testSelection: function () {
        if (window.getSelection) {
            console.log('selection range: ', document.getSelection().toString());
        }
    }
});

No matter what I select, I always get this in the console:

selection range: (an empty string)

Is there a trick to getting this to work inside backbone.js?

Thanks!


Solution

  • @adeneo is right. Once you click on the you're effectively destroying the selection range. Nonetheless, there's an easy workaround for your issue: save the original selection. Just adjust the following properties:

    events: {
        "mouseup": "testSelection",
        "click .testSelection": "getSelection"
    },
    
    testSelection: function () {
        this.currentSelection = window.getSelection();
    },
    
    getSelection: function() {
        console.log(this.currentSelection.toString());
    }
    

    The key here is to save the selection. You can do whatever you want with it later (like displaying it in the console on a <button> click).

    Note that I set our view to listen to mouseup anywhere in the view. If there's only a particular <element> (or range of elements, like all <p> in the view) that you care about, I would use that element.

    You can also check out the working fiddle. (Credit to @nikoshr for providing the base fiddle)