HTML Course 14. Integrating HTML with JavaScript (basic level)

HTML Course 14: Integrating HTML with JavaScript (Basic Level)

Integrating HTML with JavaScript allows you to create interactive web pages by manipulating the DOM (Document Object Model),
handling user events, and dynamically updating content. In this lesson, we’ll cover:

  • Including JavaScript in an HTML page
  • Inline event handlers vs. external scripts
  • Using addEventListener for cleaner event binding
  • Basic DOM manipulation: changing text, attributes and styles
  • Practical examples with commented code

1. Including JavaScript in an HTML Page

There are two main ways to include JavaScript in your HTML:

  1. Inline or internal script using the <script> tag directly in the HTML file.
  2. External script by referencing a separate .js file.

1.1 Internal Script

You can write your JavaScript code between <script> tags. Place it in the <head> or
just before the closing </body> tag to ensure the DOM has loaded.

<!-- Place this right before </body> for faster page load -->
<script>
  // Wait until the DOM is fully loaded
  document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM is ready');
  });
</script>
  

1.2 External Script

For larger projects, keep JavaScript in a separate file (e.g., app.js) and reference it:

<!-- In your HTML file, near the end of body -->
<script src='app.js'></script>
  

2. Inline Event Handlers vs. addEventListener

You can respond to user actions (clicks, input, etc.) in two main ways:

  • Inline event attributes in HTML tags (e.g., onclick), which mixes behavior and markup.
  • Using addEventListener in JavaScript for separation of concerns.

2.1 Inline Event Handler Example

<button onclick='alert('Hello from inline handler!')'>
  Click Me
</button>
  

2.2 Using addEventListener

This method keeps your HTML clean and lets you attach multiple handlers to one element.

<!— HTML —>
<button id='myButton'>Click Me</button>

<!— JavaScript in <script> or external file —>
<script>
  // Select the button by its ID
  const btn = document.getElementById('myButton');

  // Attach a click event listener
  btn.addEventListener('click', function() {
    alert('Hello from addEventListener!');
  });
</script>
  

3. Basic DOM Manipulation

JavaScript can change the page content, attributes, and styles dynamically:

  • element.textContent or element.innerHTML to update text/HTML
  • element.setAttribute / element.getAttribute
  • element.style for inline CSS changes
  • Creating or removing elements via document.createElement and parent.appendChild

3.1 Changing Text Content

<!— HTML —>
<p id='greeting'>Original text</p>
<button id='changeText'>Change Text</button>

<!— JavaScript —>
<script>
  const para = document.getElementById('greeting');
  const changeBtn = document.getElementById('changeText');

  changeBtn.addEventListener('click', function() {
    // Update the paragraph text
    para.textContent = 'Hello, the text has changed!';
  });
</script>
  

3.2 Modifying Attributes

<!— HTML —>
<img id='logo' src='logo1.png' alt='Logo'>
<button id='swapImage'>Swap Logo</button>

<!— JavaScript —>
<script>
  const logo = document.getElementById('logo');
  const swapBtn = document.getElementById('swapImage');

  swapBtn.addEventListener('click', function() {
    // Change the src attribute to a new image
    logo.setAttribute('src', 'logo2.png');
    logo.setAttribute('alt', 'New Logo');
  });
</script>
  

3.3 Dynamic Style Changes

<!— HTML —>
<div id='box' style='width:100px; height:100px; background:lightblue;'></div>
<button id='colorBtn'>>Change Color</button>

<!— JavaScript —>
<script>
  const box = document.getElementById('box');
  const colorBtn = document.getElementById('colorBtn');

  colorBtn.addEventListener('click', function() {
    // Toggle background color
    if (box.style.background === 'lightblue') {
      box.style.background = 'lightgreen';
    } else {
      box.style.background = 'lightblue';
    }
  });
</script>
  

4. Practical Example: Simple Interactive Form

Let’s build a small form that takes a name input, validates it, and displays a greeting.

<!-- HTML Markup -->
<form id='nameForm'>
  <label for='username'>Enter your name:</label>
  <input type='text' id='username' name='username' required>
  <button type='submit'>Greet Me</button>
</form>
<p id='result'></p>

<!-- JavaScript Logic -->
<script>
  // Select form and result paragraph
  const form = document.getElementById('nameForm');
  const result = document.getElementById('result');

  // Handle form submission
  form.addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent page reload

    const nameInput = document.getElementById('username').value.trim();

    // Basic validation
    if (nameInput === '') {
      result.textContent = 'Please enter your name!';
      result.style.color = 'red';
    } else {
      result.textContent = 'Hello, ' + nameInput + '! Welcome aboard.';
      result.style.color = 'green';
    }
  });
</script>
  

Key Takeaways

  • Use <script> to include JS internally or reference external files.
  • Avoid inline event handlers; prefer addEventListener for maintainable code.
  • Master basic DOM methods (getElementById, textContent, setAttribute, style).
  • Always validate user input and provide feedback dynamically.

With these fundamentals, you’re ready to make your HTML pages come alive using JavaScript.


Posted

in

by

Tags:

Comments

Leave a Reply