8

This is just the weirdest thing. I've got a Sammy.js app, and I want to set focus on a text field right after the HTML loads. I've got this CoffeeScript here:

this.partial('templates/my-template.jqt').then ->
  i = $('#item')
  debugger
  i.focus()

While I'm in the debugger, right on that line, I can inspect "i" and see that it's a JQuery object. I can even call i.val("HI THERE!") and see my text field update. But, calling i.focus() does absolutely nothing. Is there some security feature I'm missing that doesn't let you focus on a text element that was dynamically loaded?

Phil Kulak
  • 6,960
  • 8
  • 45
  • 50
  • Btw, how do you know what you can do ".then" on the partial? I can't, for the life of me, figure out what the "partial" method returns from Sammy.js api docs. How do you figure that stuff out? – Andriy Drozdyuk Jan 12 '12 at 17:44

4 Answers4

14

Try:

setTimeout(function() { $('#item').focus() }, 1);

It's quite common issue. For some reason delaying the focus for 1ms makes it working.

kazy
  • 1,111
  • 2
  • 14
  • 24
1

JQuery's focus() doesn't focus on an element, it binds an event handler to focus. http://api.jquery.com/focus/

Try i.get().focus() instead.

Gaurav
  • 12,662
  • 2
  • 36
  • 34
  • Actually, when I do $('input[type=text]').focus(), it works in Chrome, but not iOS. Here's the actual file: https://github.com/pkulak/mealfire_mobile/blob/master/coffeescripts/add_extra.coffee – Phil Kulak Nov 30 '10 at 19:33
  • 2
    When I try `i.get().focus()` in Chrome, I get "Uncaught TypeError: Object [object HTMLInputElement] has no method 'focus'". – LarsH Oct 22 '11 at 03:49
  • 2
    Also re: "JQuery's focus() doesn't focus on an element, it binds an event handler to focus": With no arguments, it does not bind an event handler; it triggers one. – LarsH Oct 22 '11 at 04:16
  • 2
    LarsH, That's because you're calling focus() on an array of elements. You can do this: i.get(0).focus() instead. – Tim Scott Apr 03 '12 at 17:56
0

If you are sure that you are getting $('#item') object.You can try out few things.

Make sure that you have only one input box with <input type="text" id="item" />.Same id should not be repeated.

Next thing is why dont you try $('#item').focus().

Thanks. with regards,

Wasim

Wazy
  • 8,822
  • 10
  • 53
  • 98
0

Do it like this:

i.trigger 'focus'
Tim Scott
  • 15,106
  • 9
  • 65
  • 79