KnockoutJS - hasFocus Binding



This binding is used to manually set the focus of a HTML DOM element through a ViewModel property. This is also a two-way binding method. When the element is focused from UI, Boolean value of ViewModel property is also changed and vice versa.

Syntax

hasFocus: <binding-value>

Parameters

  • If the parameter evaluates to true or true-like value (such as Integer or non-null objects or non-empty string) then the DOM element is focused, else it is unfocused.

  • When the element is focused or unfocused by the user manually, the Boolean ViewModel property is also changed accordingly.

  • If the parameter is observable, then the elements value is focused or unfocused as and when the underlying observable is changed. Element is processed only once, if no observable is used.

Example

Let us take a look at the following example which demonstrates the use of hasFocus binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS hasFocus Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Enter primary contact number : <input data-bind = "
         value: primaryContact,
         hasFocus: contactFlag,

         style: { 
            'background-color': contactFlag() ? 'pink' : 'white' 
         } " />
         
      </p>

      <button data-bind = "click: setFocusFlag">Set Focus</button>

      <script type = "text/javascript">
         function ViewModel() {
            this.primaryContact = ko.observable();
            this.contactFlag = ko.observable(false);

            this.setFocusFlag = function() {
               this.contactFlag(true);
            }
         };

         var vm = new ViewModel();
         ko.applyBindings(vm);
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in hasfocus-bind.htm file.

  • Open this HTML file in a browser.

  • Click Set Focus button to set the focus on the textbox.

  • The background color of the textbox is changed, when the focus is set on it.

knockoutjs_declarative_bindings.htm
Advertisements