13

I am writing a placeholder directive using angularjs.

On the click handler I want to check if the element and document.activeElement are the same.

I tried to use $docuemnt.activeElement for that but it was always undefined. But when I used $document[0].activeElement I am getting the currently active element.

Is $document[0].activeElement is the right way to access the currently active element? Or am doing something wrong?

2 Answers 2

25

No, $document is a wrapped version of document, it is wrapped using jQlite which is a tiny version of jQuery, so $document doesn't have any method called activeElement because document is inside $document, So you'll have to use

$document[0].activeElement

Or

document.activeElement

You could also create a global variable that is a wrapped version of activeElement like so.

var $activeElement = angular.element(document.activeElement);
$activeElement.attr('focused', 'yes'); // Example usage
Sign up to request clarification or add additional context in comments.

3 Comments

So you are telling i am using it the right way? Feels weird for me though.
If it feels weird then just use document.activeElement
@iConnor Why do we need to use $document[0] instead of just $document?
0

Just as an additional note is you use the above answer with:

$document[0].activeElement

Then you are actually an array of active elements so you need to use:

$document[0].activeElement[0]

or

angular.element($document[0].activeElement)[0]

Comments

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.