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
2
  • 1
    Can you try angular.element(document.getElementById("chatinput")[0]).focus(); ? Commented Jan 24, 2017 at 5:27
  • so what can i do....is there any other option. Commented Jan 24, 2017 at 5:28

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

6 Comments

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.
@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?
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.
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?Show virtual keyboard on mobile phones in javascript
i have written it after the message sending rquest
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.