Javascript in HTML to JavaScript separate

Hello,

I have a problem, I would like to move a JavaScript code in HTML into a separate file. Length puts an error message in the separate file, why?

Thanking you.

JavaScript in HTML : https://codepen.io/farangoust/pen/qBrKRry

JavaScript separate : https://codepen.io/farangoust/pen/zYZaNVm

Hello @Farangouste

if i understand what you mean that cause this option is avilable only for paid user in codepen

you can try it on your local device and has separate file for the js file and one for html

or use https://glitch.com/

hope that help and have a nice day :slight_smile:

Hello,
Thank you for your reply.
I am new to JavaScript, have gone through the courses on MDN, but I am blocking. So, I go to other resources to try to move forward. I bought a book, but the JavaScript is on the same file as the HTML. So to respect the best practices recommended by MDN, I transfer the JavaScript to a separate file.
In this case, the .length property does not work when the function is in a separate file.

you welcome
what you mean by that

did you tried as i told you by make those file on your computer not on codepen

or did you tried glitch as it offer free option and host all your files html css js

I usually work on Visual Studio Code.

When I say I’m blocking it’s because I can’t apply the lessons, I generally understand the theory, but I can’t move on to practice.

you can link the js from inside your html using the script tag
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

use the src atterbuite and give it the location of your js file

Thank you for taking the time to answer me.

The link to the Javascript file is indeed in the tag itself in the tag.

My problem is that an error message appears :
"script.js: 12 Uncaught TypeError: Cannot read property ‘length’ of undefined at HTMLInputElement.nonVide ", while it works when the JavaScript is in the HTML.

If I understand correctly, something is missing to make the connection, but I don’t know what.

you very welcome in both of the links you provide you put the js code inside the script tag you need to use the src of the script tag

go to code pen and put your html file in the html panel and the js file code into the js panel so i can read both of them in one page and see if you link them as it should be or not

As you asked me.
JavaScript in HTML :
https://codepen.io/farangoust/pen/qBrKRry
JavaScript separated from HTML :
https://codepen.io/farangoust/pen/zYZaNVm

thanks @Farangouste

looks like there was space issue

open the html file on your computer then right click on any empty space then inspect then go to the console tab you will see it complain that button is null

i just rewrite itt again in the html as follow

<input type='button' id="button" value='Validation saisie'/>

and it stop complain
hope that help and have a nice day :slight_smile:

Thank you for your help. :ok_hand:

@Farangouste you very welcome :slight_smile: