Home PHP 3 Way to Add Javascript Code in HTML

3 Way to Add Javascript Code in HTML

0
3 Way to Add Javascript Code in HTML
Add Javascript Code in HTML

On this page, you will learn how to add Javascript Code in HTML links in HTML. So you have just started with Javascript and wondering how to properly add a javascript link into an HTML file? Well, there are a few ways to include Javascript into HTML, and here is a quick answer:

Add Javascript Code in HTML

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

Define a pair of tags in the HTML and we write the javascript code between them.

You can write long JavaScript codes in separate files, as dividing the code into 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 the tag: 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 the link of the script tag. You should only use inline JavaScript when your code is 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 REPLY

Please enter your comment!
Please enter your name here