0

I am building a page with various anchors and form-elements that can be focused and I am wondering how I can get the element that is being focused on currently if something is being focused. I think one way to do it in jQuery is with .is(:focus). I'm looking for either a jQuery or vanilla js solution— just something that works.

Here is what I am trying to do in psuedo-code:

if (something is focused){
    get the tag name of that which is currently focused and store that in a variable as a string.
}
else {
    alert("nothing is being focused on");
}

Also, if you could answer this question, please do: Isn't something always focused? Meaning it is the document / body that is focused when no specific elements are or is nothing focused until done so by the code or user?

Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
IMUXIxD
  • 1,223
  • 5
  • 23
  • 44
  • @ultranaut Thank you for pointing that out. That question had the answer I am looking for. – IMUXIxD Mar 20 '13 at 16:25

3 Answers3

0

Assuming you want to do this with jQuery, you are looking for is the jQuery .prop() method. $(someElement).prop('tagName') will return the tag name of someElement.

Just threw this together, as an example: http://jsfiddle.net/kZbYv/1/

Rain
  • 363
  • 2
  • 9
0

You could use the following:

$('*:focus')
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
0

You can either set a list of elements you care about focus on, or use a wildcard selector:

$(function () {
    var focusedEls = [];
    $('*:visible').bind('focus', function (e) {
        focusedEls.push(e.target);
        console.log( $.unique(focusedEls) );
    });
});

Fiddle: http://jsfiddle.net/xfwy2/

There are a number of ways to store the elements that were focused, I just chose an array. Also, I'm not sure if you want to keep track of the times each element was focused, but if you do, just ditch the $.unique() for the full list.

couzzi
  • 6,316
  • 3
  • 24
  • 40