Search code examples
javascriptdhtml

Javascript html editor cursor focus following mouse


I use a dhtml (midas) editor as a html editor in my web application, what I want to do is get a focused cursor in this html editor follow the mouse, is there a way to do that?

Added Example: I want cursor in textarea follow the mouse so if you have a big text in your textarea and you are going over it with mouse, cursor (text cursor) should follow the mouse, like this:

"This is an ex|ample text" - if mouse is over "example" word and between x and a, text cursor (|) should be focused there but when I move mouse on for example "text" cursor | should be between letters where mouse is currently located.


Solution

  • Ok I found the solution using Ext.util.TextMetrics, first I get position of every character in editor, then I compare that to mouse cursor position and then update midas selection based on given character from charNum array

    htmlEditor.getEl().on('mousemove', function(e)
    {   
        var charNum = {},
            text = htmlEditor.getValue(),
            fWidth = htmlEditor.getWidth();
    
        var textMetrics = new Ext.util.TextMetrics(htmlEditor.getEl(), htmlEditor.getWidth());
    
        for(var n=0;n<text.length;n++)
        {
            var dat = text.substring(0, n)
            var width = textMetrics.getWidth(dat);
            var height = textMetrics.getHeight(dat);
    
            if(width > fWidth)
            {
                var mult = Math.ceil(width/fWidth)
                var width = width % fWidth;
                height = height*mult;
            }
    
            charNum[n] = [width, height];
        }
    
        //console.log("charNum: "+charNum.toSource());
    
        var mX = e.getX();
        var mY = e.getY();
    
        var cXY = htmlEditor.getEl().getXY();
        var cX = cXY[0];
        var cY = cXY[1];                    
    
        var x = mX-cX-20;
        var y = mY-cY;
    
        //console.log("fin xy: "+x+' '+y);
    
        var n = -1;
        var z = 0;
        for(key in charNum)
        {
            if(charNum[key][0] > x && charNum[key][1] > y) 
            {
                n = key-1;
                break;
            }
            n++;
            z++;
        }
    
        if(x < 0 && y < 14) n = -1; 
    
    
        if(n == (z-1) && n != -1)
        {
            n++;
        }
    
        var selection = htmlEditor.win.getSelection();
    
        range = selection.getRangeAt(0);
        range.selectNodeContents(htmlEditor.getEditorBody());
        range.collapse(true);
        for(var x=0;x<n;x++)
        {
            selection.modify("move", "forward", "character");
        }
    });