Input autofocus attribute

html autofocus not working
react input autofocus
disable autofocus html
autofocus on div
javascript autofocus
autofocus=false
input focus javascript
autofocus mdn

I have places in my code where I have this:

<input data-ng-disabled="SOME_SCOPE_VARIABLE" />

I would like to be able to use it like this too:

<input data-ng-autofocus="SOME_SCOPE_VARIABLE" />

Or even better, mimicking how ng-style is done:

<input data-ng-attribute="{autofocus: SOME_SCOPE_VARIABLE}" />

Does this exist in the current version of AngularJS? I noticed in the code there's a BOOLEAN_ATTR which gets all the attr's that AngularJS supports. I don't want to modify that in fear of changing versions and forgetting to update.

Update: AngularJS now has an ngFocus directive that evaluates an expression on focus, but I mention it here for the sake of completeness.


The current version of AngularJS doesn't have a focus directive, but it's in the roadmap. Coincidentally, we were talking about this on the mailing list yesterday, and I came up with this:

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );

                }
            });
        }
    };
});

Which works off a scope variable as you requested:

<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

Here's a fiddle: http://jsfiddle.net/ANfJZ/39/

HTML autofocus Attribute, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  Input Pattern: Use It To Add Basic Data Validation In HTML5 2,840 views How To Use The <a> To Make Links & Open Them Where You Want! 2,695 views The HTML Comment Tag: Here’s How To Use It In Your Code 2,425 views

You can do this with the built-in ngAttr attribute bindings.

<input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">

The autofocus attribute will be added if SOME_SCOPE_VARIABLE is defined (even if it's false), and will be removed if it's undefined. So I force falsy values to be undefined.

$scope.SOME_SCOPE_VARIABLE = someVar || undefined;

HTMLSelectElement.autofocus, The HTMLSelectElement.autofocus property is a Boolean that reflects the autofocus HTML attribute, which indicates whether the associated  The autofocus attribute is a boolean attribute. When present, it specifies that the element should automatically get focus when the page loads. The autofocus attribute can be used on the following elements: A button with autofocus: <button type="button" autofocus> Click Me! </button> Try it Yourself » Let the "First name" input field

This directive should do the trick:

angular.module('utils.autofocus', [])
.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    scope: {'autofocus':'='}
    link : function($scope, $element) {
      $scope.$watch 'autofocus', function(focus){
        if(focus){
          $timeout(function() {
            $element[0].focus();
          });
        }
      }
    }
  }
}]);

Taken from here: https://gist.github.com/mlynch/dd407b93ed288d499778

<input>: The Input (Form Input) element, The <input> element is so powerful because of its attributes; the The autofocus attribute cannot be used on inputs of type hidden  <input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">. The autofocus attribute will be added if SOME_SCOPE_VARIABLE is defined (even if it's false), and will be removed if it's undefined. So I force falsy values to be undefined.

scope.doFocus = function () {
                $timeout(function () {
                        document.getElementById('you_input_id').focus();
                    });
            };

HTML, The autofocus attribute in HTML is used to specify that the element should get focus when the page loads. It is a boolean attribute. Note: It supports only the  Input Attr : Autofocus Autofocus is an boolean attribute of form field that make browser set focus on it when a page is loaded. If you still don't understand what that is, please go to Google and you notice you just type your search string without first click on the big textbox.

What I did is using regular autofocus on my inputs: <input autofocus>

And then I set the focus on the first visible input with autofocus when angular is ready:

angular.element(document).ready(function() {
  $('input[autofocus]:visible:first').focus();
});

Hope this helps.

HTML5 autofocus Attribute, Another simple functionality HTML now allows us is auto-focusing on When the autofocus attribute is present, the INPUT , TEXTAREA , or  No more than one element in the document may have the autofocus attribute. The autofocus attribute cannot be used on inputs of type hidden, since hidden inputs cannot be focused. If put on more than one element, the first one with the attribute receives focus .

Autofocus Attribute, The autofocus attribute is a boolean attribute. When present, it specifies that the element should automatically get input focus when the page loads. Only one form​  When the autofocus attribute is present, the INPUT, TEXTAREA, or BUTTON element is automatically selected upon page load. I experimented with display elements ( H1 tag) and a tabIndex of 0, but autofocus did not work for them. This attribute is especially useful on pages whose main purpose is collecting

HTML5 Forms: Autofocus Type Attribute, The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be  The HTMLSelectElement.autofocus property is a Boolean that reflects the autofocus HTML attribute, which indicates whether the associated <select> element will get input focus when the page loads, unless the user overrides it. Only one form-associated element in a document can have this attribute specified.

<input autofocus> », <input autofocus>. In HTML Attributes, New. Disclosure: Your support helps keep the site running! We earn a referral fee for  The <input type="text" autofocus> is just one example of several input types that allows us to auto-focus on elements upon page load using the HTML5 autofocus attribute. This task was previously

Comments
  • @Josh, FYI, I just added a SO question about how to decide which kind of scope to use when writing a directive: stackoverflow.com/questions/14914213/…
  • Heads up: ng-focus is now a built in directive in Angular for binding callbacks to the focus event of an element. The directive here conflicts with its name
  • Do you guys know that there is a native html-attribute called autofocus. It works great, but would need some extension in angular, so that it works with updating the route.
  • ng-focus (the official one) does not perform autofocus. It evaluates an expression when the element receives focus. It's ok that it's mentioned in this answer but it doesn't address the OP's question.
  • this show us, that we should never use ng prefix for custom directives
  • Works like a charm. Thanks.
  • Nice. Working with Angular 1.5.0. Thanks.
  • This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
  • This seems wrong on so many levels... First it should be a directive as it's working with DOM itself and second browsers already implement autofocus functionality.
  • One of the anti-patterns of angular.
  • I do what works, and couldn't find an other way to make it work fine. The autofocus by browsers is buggy, depends on each browser, and doesn't work with multiple / dynamic element with autofocus
  • agreed with dorian, altough I use $timeout to wrap elm[0].focus();
  • This may have been downvoted several times, but it worked great when I had two elements and which should be autofocused depended on an ng-show directive (the first element worked, but the second wouldn't when the first was hidden).