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.


hasFocus: <binding-value>


  • 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.


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

<!DOCTYPE html>
      <title>KnockoutJS hasFocus Binding</title>
      <script src = ""
         type = "text/javascript"></script>

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

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

      <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() {

         var vm = new ViewModel();


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.