+45 70 27 40 08

sales@meeho.net

» Find out which HTML element has focus using JavaScript

Posted by Kasper Tidemann on Tuesday 5th of January 2010 04:35:55 AM

If you need to know which element on your HTML page has the current focus, you can use the document.activeElement attribute recently introduced in all the major browsers (it works in Firefox 3, Safari 4, Internet Explorer 8 etc.).

For example, this is very useful if you need to determine whether an input field has focus or not. You might have a user typing stuff in a form, and you do not wish for the user to leave the page (by mistake) in the middle of typing text in one of your input fields.

As an example of the use of document.activeElement, have a look at the following piece of code:

<html>
<head>
<title>My test page</title>
<script type="text/javascript">

 window.onkeypress = getActiveHTMLElement;

 function getActiveHTMLElement(keyevent) {

  keyevent = (keyevent) ? keyevent : ((window.event) ? event : null);

  if (keyevent) {

   switch (keyevent.keyCode) {
    case 8:
     alert(document.activeElement.tagName);
    break;
   }

  }

 }
</script>
</head>

<body>

This is my test page. Now, press backspace!

</body>
</html>

The above code will return the tag name of the element that has focus each time you press the backspace button on the page.

The document.activeElement attribute is a part of the coming HTML 5 specification. For more info, please click here and read up on the changes to come.

 

1

Kasper Tidemann

Kasper Tidemann says:

I found out an important thing that's worth mentioning: when you need Safari 4 to act upon pressing a special key like the left arrow key or the right arrow key, you cannot make Safari catch the keypress by using:

window.onkeypress

... since this supports only "normal" keys. Instead, change it to:

window.onkeydown

... and it works in Safari 4.

 

If you have something to say, feel free to drop a comment below:

Type in your name here

Type in your e-mail address here

Type in your web site address here

 

+45 70 27 40 08
Open office hours

info@meeho.net

support@meeho.net

News from the Meeho!™ Blog:

02/14 2011 » Fixing the "NoMethodError: undefined method ‘to_sym' for false:FalseClass" error when working with I18n in Ruby on Rails

02/03 2011 » Soon to come: IMAP integration

01/27 2011 » Meeho!™ App version 1.0.3 is out!

01/26 2011 » Cool new iPad stand

We live at Diplomvej 381, 2800 Kgs. Lyngby, Denmark: