Q:

How To Run JS Files In Web Server Directory

I'm new to Javascript,
When I have these two files in one directory in Desktop, It works fine,
But when i put them in the Web Server Directory /var/www/html it doesn't work
I know JS is a client side thing, but if we are building a website these .js files will be in some web server directory and should work while they are placed there
I use apache 2.4 on ubuntu 20.4
Javascript.js code :
    /*global document, console */

var mybtn = document.getElementById("mybtn");
var mydiv = document.getElementById("mydiv");
var myid = document.getElementById("myid");
mybtn.onclick = function(){
    console.log(myid.value);
    mydiv.innerHTML = myid.value;
}

.html code:
<html>
<head></head>

 <body>

<input type="text" id="myid">
<button id="mybtn">click</button>

<div id="mydiv"></div>
     
<script src="javascript.js">
     
     </script>

</body>
</html>

A:

Let's assume this is your public_html directory /var/www/html and for better code organization create a directory for javascript files as js You can do this for CSS, images and so on. So Your public directory become like this
public_html
    js
      myjscodehere.js // copy your javascript code to this file.
    css
    images
    index.html 

As for the index.html. Set a directory path to your javascript file.
<html>
<head></head>

 <body>

<input type="text" id="myid">
<button id="mybtn">click</button>

<div id="mydiv"></div>
     
<script type="text/javascript" src="/js/myjscodehere.js"></script> 

</body>
</html>

Your javascript files will work on client-side upon sending a get request to your web-server using Chrome, Mozilla and on
Separation of js code gives you many benefits such as caching to your js files and better organization if you are building a larger project it will be a problem to update your code so it is better of putting your js files into dir but it does not mean that you can not run your javascript script code inline. Yes, you can do it as following.
<html>
    <head></head>
    
     <body>
    
    <input type="text" id="myid">
    <button id="mybtn">click</button>
    
    <div id="mydiv"></div>
         
    <script type="text/javascript">

var mybtn = document.getElementById("mybtn");
var mydiv = document.getElementById("mydiv");
var myid = document.getElementById("myid");
mybtn.onclick = function(){
    console.log(myid.value);
    mydiv.innerHTML = myid.value;
}

    </script> 
    
    </body>
    </html>

And since javascript code runs on the client-side. You can run it in your windows machine using a web browser and you do not need web-server. The purpose of pushing your js file or the whole project to the web-server is that your clients or people who visit your web site to use your online app in their local machines.

