Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto focus a field?

I'm writing a small chat client/server app with KnockoutJS and Node.js, everything is good, except for the fact, that after I send a message, I lose focus on the message field, and users have to reclick it everytime they want to type (very annoying). Do you guys know what I can do? Here is the template:

<script type="text/html" id="chatRoom">
<div id="chatContainer" class="chatContainer">
    <div class="chatFrom">
        <i id="chatClose" class="chatSprite chatClose" data-bind='click: function() { server.removeChat(this) }'></i>
    </div>
    <div class="chatMessages">
        <ul id="chatHolder">
        {{each messages()}}
            <li><div class="chatFromText">From: ${ from }</div>
            <div class="chatTime">${ time }</div><div class="chatMsg">${ text }</div></li>
        {{/each}}
        </ul>
    </div>
    <div class="chatControls">
    <form data-bind="submit: function() { send($('#'+channel).val()); $('#'+channel).focus(); }">
        <input type="text" id="${ channel }" name="message" class="chatText" style="color: #999;" value="Message Here" data-bind='click: function() {
            $("#"+channel).val("").css("color", "#000");
        }'  />
        <i class="chatSprite chatSend" data-bind="click: function() { $('.chatSend').parent().submit() }"></i>
    </form>
    </div>
</div>
</script>

As you can see I have tried every possible way of focusing the field, but none seem to work. Any suggestions?

like image 841
Jose Avatar asked Mar 08 '11 20:03

Jose


2 Answers

I think that your issue is likely that your "send" method does an asynchronous post back to the server, in the success callback it probably pushes the message to your messages observableArray. When this happens your template is re-rendered and your focus is lost. So, this happens after your $('#'+channel).focus() call, because the send completes asynchronously.

Can't be sure without seeing your send function.

One option would be to pass "channel" as another parameter to your "send" function, then in the success callback for your AJAX request after pushing the message to your messages observableArray set the focus based on channel.

Sample here: http://jsfiddle.net/rniemeyer/h2A6p/

like image 141
RP Niemeyer Avatar answered Oct 18 '22 01:10

RP Niemeyer


Knockout now has a hasfocus binding.

like image 31
Aran Mulholland Avatar answered Oct 17 '22 23:10

Aran Mulholland