knockout hasFocus event not firing click event works, but doesn't "unclick" Using version 3.4.2

300 views
Skip to first unread message

Ian

unread,
Dec 3, 2017, 12:25:49 AM12/3/17
to KnockoutJS
Hello, 

Have a simple test page.  And having trouble getting the CSS class "search-bar-focused" to appear on the form element when the input element has focus.   I also want to remove the class when the input element loses focus, but I'm not quite sure how to do that with knockout.   The CSS class "search-bar-focused" seems to get added/inserted into the class attribute if I use "click" instead of "hasFocus."   But if I click outside of the input box, the css class "search-bar-focused" doesn't get removed.

HTML Markup:

<HTML>
<head>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="knockout-3.4.2.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript" defer="defer"></script>
</head>
<body>
<form action="/search" method="get" class="input-group search-bar" role="search" data-bind="css: { 'search-bar-focused': isFormFocused }">
<input type="search" name="q" class="input-group-field"
aria-label="Search Site" autocomplete="off" data-bind="hasFocus: setFormFocused">
</form>
</body>
</HTML>

myscript.js:

var viewModel = {isFormFocused: ko.observable(false),
setFormFocused: function() {
this.isFormFocused(true); }
};

ko.applyBindings(viewModel);

Michael Best

unread,
Dec 3, 2017, 1:03:34 AM12/3/17
to KnockoutJS
hasFocus should be bound to the observable. So the binding will be "hasFocus: isFormFocused"

Ian

unread,
Dec 3, 2017, 1:59:32 AM12/3/17
to KnockoutJS
Thanks for your help.   Can you tell me exactly where I need to do this binding to the observable; e.g. not clear on where it needs  "hasFocus: isFormFocused"?

Andrew Vickers

unread,
Dec 3, 2017, 11:12:35 AM12/3/17
to KnockoutJS
    <form action="/search" method="get" class="input-group search-bar" role="search" data-bind="css: { 'search-bar-focused': isFormFocused }">
     <input type="search" name="q" class="input-group-field"
      aria-label="Search Site" autocomplete="off" data-bind="hasFocus: isFormFocused">
   </form>

You only need the set function if you want to add the class programmatically.
Reply all
Reply to author
Forward
0 new messages