TypeError: prc.cng () is not a function in Firefox, Uncaught TypeError: Object # <HTMLInputElement> does not have a cng method in Chrome
I am writing a small library for internal use in the project I'm working on, I am an amateur Javascript developer, so please think about my mistakes.
I wrote a small html file as well as javascript below,
<html> <head> <script> var prc = { cng : function(evt){ console.log(evt); } } </script> </head> <body> <input type='text' id='prc' onkeydown="prc.cng(window.event)"/> <body> </html> I tried to accomplish this in Firefox and Chrome, and not in IE Still,
When I try in Firefox, it gives this error "TypeError: prc.cng is not a function" , and when I try in chrome it gives "Uncaught TypeError: Object #<HTMLInputElement> has no method 'cng'" .
I tried to find this on StackOverflow, but the problems they are facing are very different from what I am facing. Almost all the problems were related to jQuery, please note here that I am not using any library or writing with plain old Javascript.
Any help would be appreciated to improve my understanding of the problem.
Having an element with id that matches an existing JS variable smooths the contents of the variable and replaces it with a link to the element.
A quick fix is ββto change the variable name or element identifier.
A more robust solution would be to keep all your data as narrow as possible. If you do not need it to be global, then do not make it global, and it will not be overwritten from outside the script.
Since, using the attributes of inline events, you can only refer to variables in <script> elements, if they are global, this is also a good time to stop using them and move on to something modern.
// Self-executing anonymous function expression used to limit scope (function () { // Locally scoped prc that won't clash with the element var prc = { cng : function(evt){ console.log(evt); } } // Event handler binding document.getElementById('prc').addEventListener('keydown', function (evt) { prc.cng(evt) }); }()); Note that this script does not delay execution until load or domReady , so place it after input so that the input exists when trying to find an event handler.
I found the answer to my question thanks to @Barmar, which helped me understand the problem.
When I define any element in html like this
<input type='text' id='test' onkeydown='test.fn()'/> This means that the same object is created for the browser. So, if I have written javascript that encounters id, it will not be available anywhere on this page.
<script> var test = { fn : function(){ console.log('test'); } } </script> Thus, it is ideal to either rename the id, or rename the object.