How to add JavaScript into Html


JavaScript, also called "JS" in abbreviation, is a high-level, interpreted scripting language that conforms to the ECMAScript specification, and which is the most popular technology for the web, alongside HTML, and CSS.

Including JavaScript to your Html project or web page is a great choice, because there are so many features it will integrate into your Html page. Such as making your web page dynamic, handling dates and times, giving you control over the browser, and many more.

So now you've discovered the importance and powers of JavaScript, let's begin adding it to our HTML file right away!!.

Including JavaScript in your web page

There are two ways to include JavaScript to your web page
  • Directly into your HTML file
  • Including it as an external file

1. Directly into HTML

Within your HTML file, JavaScript can be placed in the <head> or <body> section.


*In the head section:

Example:

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>
Source:https://www.w3schools.com/js/js_whereto.asp


*In the body section:

Example:


<!DOCTYPE html>
<html>
<head>

</head>
<body>

<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>


What the above examples do is to change the text in the paragraph tag to something else.

2. Including JavaScript as an external file.

You can also include an external JavaScript file using the <script> tag and a src attribute pointing to the path of your JavaScript file.

Example:


<script type="text/javascript" src="path-to-javascript-file.js"></script>

The <script> tag should be placed inside the <head> section.


Note: only JavaScript codes should be in your JavaScript file, and the file name should have a .js extension.

Post a Comment

0 Comments