0

I have written the following lines to add focus on an input element in angular js:

angular.element(document.getElementById("chatinput")).focus();

but is not working an giving an error:

angular.element(...).focus is not a function
abhit
  • 973
  • 3
  • 17
  • 40

1 Answers1

3

The "jqLite" library that's included with Angular for angular.element() doesn't include the .focus() method.

To make it available, you'll have to load the jQuery library before loading Angular and your application code. Once you've done that, angular.element() will be an alias of jQuery instead of jqLite.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/path/to/angular.js"></script>

Or, the Element returned from getElementById() has its own .focus() method that you can call without using angular.element():

document.getElementById("chatinput").focus();

// though, you may want to check that it's found first
var chatinput = document.getElementById("chatinput");
if (chatinput) chatinput.focus();
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • this is not working. i have applied this logic on my send button so that whenever i send a message the input field (chatinput) gets focus again and the keyboard doesn't closes. – abhit Jan 24 '17 at 05:44
  • @lakshay Sorry. What exactly isn't working? Is what you described what you expected to happen or what you're seeing happen when you try it? And, in either case, what's the behavior for the other? – Jonathan Lonowski Jan 24 '17 at 05:55
  • i am trying to create a chat module in which I have an input field and a send button now every time I send an message the keyboard closes as the input field loses its focus and i don't want my keyboard to close every time i send a message therefore I am trying to maintain focus on my input field after sending the message. – abhit Jan 24 '17 at 05:57
  • When are you trying to set the focus? I assume sending the message involves something asynchronous (Ajax, etc.). If so, you may need to set focus before the message has completed, while the browser is still working with the call stack for the submit/click event (callbacks run in separate stacks). – [Mobile Safari: Javascript focus() method on inputfield only works with click?](https://stackoverflow.com/questions/12204571/) – [Show virtual keyboard on mobile phones in javascript](https://stackoverflow.com/questions/6837543/) – Jonathan Lonowski Jan 24 '17 at 06:02
  • i have written it after the message sending rquest – abhit Jan 24 '17 at 06:17
  • @lakshay Ok. Try instead setting focus right before sending the message to the server. – Jonathan Lonowski Jan 24 '17 at 06:20