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