skip to Main Content

I am listening for selectionStart and selectionEnd with knockout and it’s working fine when the user clicks with the mouse and drags rightward to create the selection. But if the user clicks in the text and drags the mouse leftwards to create the selection, the proper values are not being returned: selectionEnd and selectionStart are in that case the same value, e.g. 6 and 6 when I select a six-letter word moving right-to-left with the mouse.

Here’s my binding:

<input type="text" data-bind="textInput: Model.searchWord, event:{keyup: Model.saveSelection, mouseup: Model.saveSelection, mousedown: Model.saveSelection, click: Model.saveSelection}" />

P.S. I’ve also tried without listening for the click event.

and here’s the code:

    self.selectionStart = ko.observable();
    self.selectionEnd = ko.observable();

self.saveSelection = function (v1, keyEvent) {
        
        self.selectionStart(keyEvent.target.selectionStart);
        if (keyEvent.target.selectionEnd) {
            self.selectionEnd(keyEvent.target.selectionEnd);
        } else {
            self.selectionEnd(0);
        }    

    if (keyEvent.type == "mousedown") return true;
    if (keyEvent.type == "mouseup") return true;            
      
    }



      

2

Answers


  1. Chosen as BEST ANSWER

    In my case I'm working with a home-grown virtual keyboard that injects characters not found on the user's keyboard into the observable backing the Input element. Sometimes it will be an appended or inserted character, and sometimes it will replace a selection. So the selection start and end values have to be captured in the blur event as well.


  2. There is an error in your JavaScript example:

     if (keyEvent.type = "mousedown") return true;
     if (keyEvent.type = "mouseup") return true; 
    

    You’re assigning to keyEvent.type instead of doing a comparison. Try:

     if (keyEvent.type === "mousedown") return true;
     if (keyEvent.type === "mouseup") return true; 
    

    I have a working example that shows selection correctly at: https://playcode.io/1351651

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search