Search code examples
angularjsinternet-explorerangular-ui-bootstrapmozillamicrosoft-edge

Show text from beginning when text is longer than textbox's width


When some text is added in an input field and text exceeding its width. Now when the focus is shifted outside the input field (blurred), I want to show its text from beginning (not where the user stopped typing).

In Chrome, it is working by default i.e. when the focus is lost from the input field, the Chrome automatically moved the cursor to the beginning of the text.

In Mozilla, EDGE, IE this behaviour is not working.


Solution

  • It's very simple. Create a directive and use the answer from: move cursor to the beginning of the input field?

    Run this example on Mozilla

    var app = angular.module("sa", []);
    
    app.directive("fixCursorFoo", function () {
        return {
            restrict: 'A',
            link: function ($scope, $element) {
                $element.on("blur", function () {
                    var inp = $element[0];
                    if (inp.createTextRange) {
                        var part = inp.createTextRange();
                        part.move("character", 0);
                        part.select();
                    } else if (inp.setSelectionRange) {
                        inp.setSelectionRange(0, 0);
                    }
                })
            }
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    
    <div ng-app="sa">
      <input type="text" fix-cursor-foo class="form-control" />
    </div>