2

I have just stumbled upon the following webpage and am somewhat intrigued by the use of the in keyword.

http://diveintohtml5.ep.io/examples/input-autofocus-with-fallback.html

  • Is this valid JavaScript?
  • Do all browsers accept this?
  • How does it actually work?

They are using this syntax for fallback when web browser doesn't support the autofocus attribute. So this would lead me to believe that this syntax is valid.

DanBeale
  • 310
  • 4
  • 15
Lea Hayes
  • 62,536
  • 16
  • 62
  • 111

3 Answers3

5

The in operator checks if a property is defined on an object. So, this is valid Javascript and is accepted in almost all browsers.
In this case, the code is checking if "autofocus" is a property of a new element. If it is, then most likely the browser supports autofocus and will not need .focus() (or someone may be extending prototypes).

Digital Plane
  • 37,354
  • 7
  • 57
  • 59
4

You can think of it like this:

"localStorage" in window; // true
!!window["localStorage"]; // true
window["localStorage"] !== undefined; // true

These statements are basically the same.

Joe
  • 80,724
  • 18
  • 127
  • 145
1

"autofocus" is an arbitrary boolean attibute that the script looks for. It's really no different than <input id="q" class="autofocus">, except in this case, the script would need to look for the class name (which a lot of validation scripts usually use) versus the attribute.

The browser doesn't "support" it, the script makes it work.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176