asc99c
asc99c

Reputation: 3905

IE10 - avoid form names in global scope for javascript

I've got a web application with a search box, and an onKeypress event calls Query.keyPress(). Query is defined in an included javascript file. Most of the time this works correctly.

On IE10 from some screens, trying to use the search box gives an error:

Error: Object doesn't support property or method 'keyPress'

What I have found is some of the screens have a query form with a name and id of 'Query'. It seems in IE10 this appears in the global scope, and overrides the object literal from the javascript. For info, the search box is not inside this form.

I've replaced the onKeypress code with alert(Query); and I see [object HTMLFormElement] which confirms what is happening.

Does anyone know how to stop this happening on IE10?

Upvotes: 1

Views: 422

Answers (2)

Matt
Matt

Reputation: 75317

This problem can be negated by using your own namespace, rather than polluting the global scope time and time again.

var MY_STUFF = {};

MY_STUFF.Query = function () {};
MY_STUFF.MY_CONST = 4;
MY_STUFF.utilityFunction = function () {};

... this way, everything breaks if you add a form element named MY_STUFF, but it won't break if you add form elements called Query, MY_CONST or utilityFunction (not the best names, but you get the gist).

Like I said, it doesn't fix the problem, but it negates it. Polluting the global scope is also a bad practise.


You can, of course, not use a global variable at all, through closures. But this will likely require a lot of restructuring, if you have your application spread over multiple files, and no build process in place to combine your files.

(function () {
    var Query = function () {};

    // Query.keyPress() as much as you want!
}());

// Note you can't use it outside of the closure.

Upvotes: 2

Parthik Gosar
Parthik Gosar

Reputation: 11646

Probably, this should work. When declaring your variable Query, provide a var keyword before it.

var Query = new Object (); //right practice

Query = new Object (); //wrong practice

Upvotes: 0

Related Questions