JavaScript Tutorial – 4 Ways to Write Javascript Code in HTML

In this tutorial, we discuss 4 Ways to Write JavaScript Code in HTML for beginners, Javascript as a programming language that runs on top of the browser must be written in HTML. There are four ways to write javascript in HTML.

1. Tag <script>

The common method used is to write it in the <script> tag. The <script> tag can be made in the <head> tag, whatever in the <body> tag. Example:

<! DOCTYPE html>
<html>
<head>
   <meta charset = "utf-8">
     <title> Writing Javascript </title>
   <script> console.log ("Hi, this is Javascript code");
   </script>
</head>
<body>

   <script> document.write ("Javascript is cool!");
   </script>
</body>
</html>

2. External Files

Do not want the Javascript code to mix with HTML, we can write it in a separate file. The trick, make a file with the extension .js, for example, the contents are as follows.

// file-external.js
alert ("Javascript Code from External Files");

Then, we need to connect the external file with the HTML file. The method is to use the <script> tag with the src attribute to determine the location of the Javascript file.

<! DOCTYPE html>
<html>
<head>
     <meta charset = "utf-8">
     <title> Writing Javascript </title>
     <script src = "file-external.js">
     </script>
</head>

<body>
</body>
</html>

3. Event Attributes

The third method is often used to call functions at certain events. For example when an element is clicked, then run the Javascript function.

<button onclick = "alert ('Ok Thank you!')"> Click on done! </button>
Besides onclick events, there are also other events, such as submit, onload, ondoubleclick, onmouseover, onmouseout, etc.

4. URL

Finally, write Javascript in the URL. This method is rarely used, but we also need to know it. Writing Javascript on a URL using the Javascript protocol. For example, try to write code like this in the browser URL.

javascript: alert ("Well! This is JavaScript")

The result, Javascript will be executed by the browser.

Then, how do we use this method in HTML?

This method can be used in the <a> tag, then fill in the javascript code in the href attribute. This method can replace the onclick event.

<a href="javascript:alert('Wih! great isn't it?')"> Click Me </a>

That’s the four ways to write Javascript in HTML. Which way do you use often?

Sending
User Review
0 (0 votes)

Add a Comment

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