Integrating HTML with JavaScript

HTML (Hypertext Markup Language) and JavaScript are essential technologies for creating dynamic and interactive web pages. Here's a detailed guide on how to integrate HTML with JavaScript, covering various methods to include JavaScript code in HTML documents.

  1. Inline JavaScript
    • Inline JavaScript code is placed directly within HTML tags using the on event attributes.
    • Example:
      <button onclick="alert('Hello, Coders!')">Click me</button>

    • Pros: Quick and easy for simple actions.
    • Cons:Not recommended for complex scripts due to maintainability issues.


  2. Internal JavaScript
    • Internal JavaScript is embedded directly within the HTML file using the <script> element.
    • Example:
       <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Internal JavaScript</title> 
      </head>
          <button onclick="showMessage()">Click me</button>
      
      <script>
          function showMessage() {
              alert('Hello, Coders!');
          }
      </script>
      </body>
      </html>
      

      output:-

    • Pros: Keeps scripts within the HTML file.
    • Cons: Limited reusability, especially in larger projects.


  3. External JavaScript
    • External JavaScript involves creating a separate JS file and linking it to the HTML file.

    • script.js
      // script.js
      
      function showMessage() {
          alert('Hello, World!');
      } 

      index.html
          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title>External JavaScript</title>
              <script src="script.js"></script>
          </head>
          <body>
              <button onclick="showMessage()">Click me</button>
          </body>
          </html>