-1

Javascript syntax

for(i in x) { x[i].focus(); }

This works properly in Mozilla and Chrome but gives error in IE.

Error displayed is

Message: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.

I tried using try catch block as below

for(i in x) { try { x[i].focus(); } catch(err){ } }

It worked properly, but My system has more than 100 pages and dont know how many times i have used .focus

Kindly help me get rid of this IE problem.

2 Answers 2

3

This error happens when you try to focus() an element that can't take focus (as the error says). To get rid of it, implement a method that does the necessary checks before calling focus on the element. E.g.

function focusElement(el) {
  var canFocus = !el.disabled &&
                  el.style.display != 'none' &&
                  el.style.visibility != 'hidden';
  if (canFocus) el.focus();
  return canFocus;
}

... then your code would look like:

for (i in x) focusElement(x[i]);

(BTW, 'seems odd that you would focus() more than one element at a time, since only the last element will be left with the focus.)

2
  • No I wont focus all the elements as u said in last sentence.. Its like there is a condition which checks if x==y then focus.. Also the solution provided by you is good but as .focus is used n number of times in my system .. how many places i will make the changes.. I need some universal patch for it Commented Apr 15, 2011 at 11:21
  • You can't extend the builtin HTMLElement.prototype in IE which is the only way you'd be able to patch this without having to change your code that currently calls focus(). However if you use a library like jquery or Prototype, and are accessing your elements through the APIs those libraries provide, they do have mechanisms for enhancing DOM elements. See prototypejs.org/learn/extensions
    – broofa
    Commented Apr 15, 2011 at 16:35
0

This could be because for ( i in x ) will also return all other attributes of the x object.

So, if this is an array, it will return length as well, and the code will try to invoke 'focus()' on the integer number which does not exist.

I would modify the code to check on the presence of focus method first.

So: for(i in x) { if (x[i].focus) { x[i].focus(); } }

You may add try/catch as well.

2
  • Not the problem. Calling an undefined method will yield " "Object doesn't support this property or method" error, not the error the OP describes.
    – broofa
    Commented Apr 15, 2011 at 11:04
  • It not what my problem is, my problem is that there are n number of times i have used .focus and every time i might get error. So I need some kind of solution for IE such that this errors doesnt comes up. Commented Apr 15, 2011 at 11:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.