How to Put the JavaScript Code in HTML Page

How to Put the JavaScript code in HTML Page with Example.

You can include JavaScript in an HTML page in three main ways:

  1. Inline JavaScript – Directly within an HTML tag.
  2. Internal JavaScript – Inside <script> tags within the HTML document.
  3. External JavaScript – In a separate .js file linked to the HTML page.

Here’s an example demonstrating all three methods:

1. Inline JavaScript
JavaScript is added directly to an HTML element using the onclick attribute.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Inline JavaScript Example</title> </head> <body> <h1>Inline JavaScript</h1> <button onclick="alert('Button Clicked!')">Click Me</button> </body> </html>

Explanation:

  • When the button is clicked, the onclick attribute triggers the alert() function directly.
2. Internal JavaScript
JavaScript is placed inside the HTML file but within <script> tags.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Internal JavaScript Example</title> </head> <body> <h1>Internal JavaScript</h1> <p id="text">Click the button to change this text.</p> <button onclick="changeText()">Click Me</button> <script> function changeText() { document.getElementById("text").innerText = "Text changed by JavaScript!"; } </script> </body> </html>

Explanation:

  • The <script> tag is placed within the same HTML file, but the JavaScript logic is separate from the button.
3. External JavaScript
JavaScript is written in a separate file (script.js) and linked to the HTML using the <script> tag.

HTML (index.html):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>External JavaScript Example</title> </head> <body> <h1>External JavaScript</h1> <p id="message">Click the button to change this text.</p> <button onclick="updateText()">Click Me</button> <script src="script.js"></script> </body> </html>

JavaScript (script.js):

    function updateText() {     document.getElementById("message").innerText = "Updated from external JS file!";     }

Explanation:

  • The JavaScript code is stored in script.js.
  • The HTML file links to it using the <script src="script.js"></script> tag.

Best Practices:

  • Use external JavaScript for better code organization and reusability.
  • Place <script> tags before the closing </body> to ensure the HTML loads before JavaScript is executed, improving performance.

Post a Comment

Previous Post Next Post