Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript good practices: remove inline onsubmit(), global variables

I'm learning good practices with JavaScript (btw, if you have articles about it to recommend me, I'll be grateful :D) and I have some questions about:

  1. onsubmit(), onclick() and other inline functions
  2. What should I do when the variable is global
  3. open() method

About 1 and 2

I have a form in my HTML page and I was using this way:

<form name="myForm" onsubmit="myFunction();">

Inline JS is a bad practice and I must remove it. So, I removed onsubmit="myFunction();" and add in my JS (in a external file):

var form = document.myForm;

form.onsubmit = function myFunction() { /* codes hidden here */ };

But...

1. Why my code is not working? I have to use window.onload before? Sometimes I don't know when I should use it.

2. Once I read that I should not declare global variables (like form above). How can I make a local variable in that case then?

About 3

3. In a function I generate a URL and the user clicks on a button to open it. But I read that open() is a bad practice. Is this true? If yes, how to replace?

like image 725
kratos Avatar asked Feb 19 '26 02:02

kratos


1 Answers

When the statement:

var form = document.myForm;

is evaluated, the form must exist in the DOM, otherwise form will be undefined. If the above is in the head, then when the code is executed and the assignment made the form almost certainly wont exist yet.

Any values that are dependent on DOM elements should be assigned after the DOM has loaded. The simplest way to ensure that is to place scripts immediately before the closing body tag.

There are other methods that load scripts on the DOMReady event (or similar) or wait for the window's load event, but that can cause a delay between when elements are visible and the script runs.

form.onsubmit = function myFunction() { /* codes hidden here */ };

If form is undefined you're in trouble… :-(

It is also a good idea to give global variables names that are unlikely to clash with standard globals (there are quite a lot of them, e.g. many browsers make all element names and IDs into global variables referencing the element to be compatible with ancient IE code), so better to do something like:

var formElement = document.forms['myForm'];

or better yet, keep your global variable count as low as is reasonable (zero is possible but not always sensible). e.g. you could do:

window.onload = function() {
  var form = document.myForm;
  form.onsubmit = function myFunction() { /* codes hidden here */ };
}

in code that is in the head. Or something like Kyle Weller's answer close to the closing body tag instead.

like image 196
RobG Avatar answered Feb 21 '26 15:02

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!