3 Way to Add Javascirpt Code in HTML

Welcome to thewholeblogs.com on how to add javascript link in HTML. So you have just started with Javascript and wondering how to properly add javascript link into an HTML file? Well, there are a few ways to include Javascript into HTML, and here is a quick answer:

(“1.”) you can use tag in HTML. And

Define a pair of  tags in the HTML and we write the javescript code between it.

You can write long JavaScript codes in separate files, as dividing the code in portions makes it more readable.

It is suggested to only implement short JavaScript codes inside the  tag. Otherwise, the code can become hard to read.

First, we’ll show you how you can add javascript in HTML using the tag: The example below shows a JavaScript myFunction().

<!DOCTYPE html>
<html>
<head>
    <script> 
      function myFunction() { 
         document.getElementById("click").innerHTML = "thewholeblog.com!"; 
      } 
   </script> 
</head>
<body>
   <h1>A Web Page</h1>
   <p id="click">thewholeblog.com?</p>
   <button type="button" onclick="myFunction()">Answer!</button>
</body> 
</html>      

The second way you can use in intag: Our next example defines how JavaScript myFunction() function, which is called upon a button click, is placed in the  section.

<!DOCTYPE html>
<html>
<body>
   <h1>Thewholeblog.com</h1>
   <p id="click">thewholeblog.com?</p>
   <button type="button" onclick="myFunction()">Answer!</button>
   <script> 
      function myFunction() { 
         document.getElementById("click").innerHTML = "I love learning JavaScript!"; 
      } 
   </script>  
</body>
</html>

External JavaScript:

The three and last way is link of script tag. You should only use inline JavaScript when your code just a few lines .In other cases, you should place your JavaScript code in a separate file and link it to your HTML file. The external script will behave the same way as it would when written in a <script> tag. Let’s take a look.

function myFunction() {     
   document.getElementById("example").innerHTML = "I love JavaScript!";  
}

Leave a Comment