How to link JavaScript to HTML?

how to link javascript to html

JavaScript is a well-known scripting language that’s used both on the client-side and on the server-side. JavaScript is important for our web pages as it ensures we have an interactive web page. With web pages, you need to do more than just display content. You are required to load JavaScript. Among the first JavaScript, files to be added is Google Analytics which helps in tracking page loads & visitors.

how to link javascript to Html?

One can add JavaScript-code in a HTML document through employing a devoted HTML tag <script> which wraps in JavaScript code.

A <script> tag can be positioned at the <head> section of HTML or at the <body> section. This depends on when you need to load the JavaScript. A JavaScript code can move inside the document <head> section for it to be contained & out of the major content of the HTML document

Linking JavaScript files to HTML is simple. All that’s needed is to place just one line that’s simple to compose. You need to utilize <script> tag together with “SRC” Attribute to achieve this.

Advance HTML5 and HTML Interview Questions

A). Link Direct JavaScript File

<script src="myscripts.js"></script>

Remember to replace “myscripts.js” with your JavaScript file name.

B). Link-File Inside Folder

When the JavaScript file is in the folder you need to write the code this way

<script src="foldername/myscripts.js"></script>

Replace the folder name with an actual folder’s name & myscript.js using your original JavaScript file.

C). If HTML & JavaScript all Inside Folder

If your HTML file is not in the root or it’s inside the folder and the js file is in another folder. Then you have to write the script like below.

<script src="../foldername/myscripts.js"></script>

../” moves you inside the parent directory. Thus, the server offers you access to JS file & operate on the client-side.

Example

JavaScript added below <head> tags


<!DOCTYPE html> <html> <body> <h2>JavaScript ISO Dates</h2> <p id="demo"></p> <script> const d = new Date("2015-03-25"); document.getElementById("demo").innerHTML = d; </script> </body> </html>

Output

JavaScript ISO Dates

Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)

RECENT POST

Terry White

Terry White is a professional Drupal & WordPress developer, Web developer, Web designer, Software Engineer, and Blogger. He strives for pixel-perfect design, clean robust code, and a user-friendly interface. If you have a project in mind and like his work, feel free to contact him

View all posts by Terry White →

Leave a Reply

Your email address will not be published. Required fields are marked *