Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs $document[0].activeElement instead of $document.activeElement

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?

like image 398
Anirudhan J Avatar asked Sep 26 '13 17:09

Anirudhan J


People also ask

Can document activeElement be null?

activeElement should never return null, it doesn't mean that in the future such browsers will hold fast to this rule.

What is document activeElement returns?

activeElement. The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus. Often activeElement will return a HTMLInputElement or HTMLTextAreaElement object if it has the text selection at the time.

What is activeElement?

An active element is an element capable of generating electrical energy. The essential role of this active element is to magnify an input signal to yield a significantly larger output signal.

How do you know which element is focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.


1 Answers

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
like image 152
iConnor Avatar answered Oct 11 '22 11:10

iConnor