Categories
JavaScript Web development

How to add JavaScript to HTML?

In some of my previous posts started appearing JavaScript, so why today I would like to explain more how to nest the code into HTML. You will learn more about JavaScript in later chapters, but today in a short introduction to the post you need to know what JavaScript is and what JavaScript can do.

How to add JavaScript to HTML?

JavaScript is the programming language for the web and can update and change both HTML and CSS.

You can place any number of scripts in your HTML document.

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want Java Script to load. 


In this example, a JavaScript function is placed in <head> section of HTML page. The function is invoked (called) when a button is clicked: 

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

<h4>JavaScript in the Head Section</h4>

<p id="example">Click on the button to change the text.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html> 

Output:

JavaScript in the Head Section

Click on the button to change the text.


Hope you find it helpful.

Enjoy coding!