DOM Manipulation using Javascript : Part 2

  Introduction to DOM : Part 2

    Dive deeper into event handling, style manipulation, and working with forms

In the first part of this series, we explored the basics of the Document Object Model (DOM) and how to use JavaScript to interact with HTML elements dynamically. In this second part, we will build upon that foundation by exploring event handling, modifying styles dynamically, and working with forms to handle user input.

Event Handling in the DOM

One of the most powerful features of the DOM is event handling. Events allow us to respond to user actions like clicks, mouse movements, key presses, and more. These interactions enable us to create dynamic and responsive web applications.

1. Attaching Event Listeners

You can attach an event listener to an element to detect and respond to specific events. The most common approach is to use the addEventListener() method, which allows us to listen for a particular event (like a click or hover) and execute a function when that event occurs.

Here's a simple example that shows how to handle a click event:


 
<html lang="en">
<head>
  <meta charset="UTF-8"></meta>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"></meta>
  <title>Event Handling Example</title>
</head>
<body>
  <button id="changeButton">Click me to change color!</button>

  <script>
    // Select the button element
    const button = document.getElementById("changeButton");

    // Define the event listener function
    function changeColor() {
      document.body.style.backgroundColor = "lightblue";
    }

    // Attach the event listener to the button
    button.addEventListener("click", changeColor);
  </script>
</body>
</html>

How it works:

  1. The addEventListener() method attaches the changeColor function to the click event of the button with the id changeButton.
  2. When the button is clicked, the background color of the page will change to light blue.
2. Event Types
There are many types of events you can listen for. Some of the most common ones include:
  • Click (click): Triggered when an element is clicked.
  • Mouse Events (mouseover, mouseout, mousemove): Triggered when the mouse interacts with an element.
  • Keyboard Events (keydown, keyup, keypress): Triggered when a user presses or releases a key.
  • Form Events (submit, input, change): Triggered when a user interacts with form elements.

  • Focus Events (focus, blur): Triggered when an element gains or loses focus.

For example, we could use the keydown event to log the key pressed by the user:


document.addEventListener('keydown', function(event) {
  console.log("You pressed the key: " + event.key);
});

Modifying Styles Dynamically

One of the most common use cases of DOM manipulation is changing the style of elements dynamically. JavaScript can modify CSS properties directly, which allows us to create interactive user experiences.

1. Inline Styling

You can modify an element's style directly through JavaScript using the style property:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Style Manipulation Example</title>
</head>
<body>
  <button id="styleButton">Click me to change my style!</button>

  <script>
    // Select the button element
    const button = document.getElementById("styleButton");

    // Change the button's style
    button.addEventListener("click", function() {
      button.style.backgroundColor = "green";
      button.style.color = "white";
      button.style.fontSize = "20px";
    });
  </script>
</body>
</html>

How it works:

  • When the button is clicked, its background color is changed to green, text color to white, and font size to 20px.
  • The style property allows you to directly modify CSS properties of the element.


2. Adding and Removing Classes

Another common way to manipulate styles is by adding or removing CSS classes dynamically. This allows you to keep your CSS separate from JavaScript and take advantage of pre-defined styles.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Class Manipulation Example</title>
  <style>
    .highlight {
      background-color: yellow;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <p id="text">Click the button to highlight this text!</p>
  <button id="highlightButton">Highlight</button>

  <script>
    const text = document.getElementById("text");
    const button = document.getElementById("highlightButton");

    button.addEventListener("click", function() {
      text.classList.toggle("highlight");
    });
  </script>
</body>
</html>

How it works:

  • The classList.toggle() method adds the highlight class to the text element when the button is clicked. If the class is already present, it will be removed.
  • This method is a great way to toggle styles based on user interactions.


Working with Forms

Forms are essential for gathering user input on webpages. DOM manipulation can be used to validate form data, change input values, or respond to form events.

1. Accessing Form Elements

You can access form elements by their id, name, or class attributes using the same methods we’ve discussed (e.g., getElementById(), querySelector()).


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Example</title>
</head>
<body>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Submit</button>
  </form>

  <script>
    const form = document.getElementById("myForm");

    form.addEventListener("submit", function(event) {
      event.preventDefault();  // Prevent the form from submitting

      const name = document.getElementById("name").value;
      alert("Hello, " + name + "!");
    });
  </script>
</body>
</html>

How it works:

  • The form submission is intercepted with the submit event.
  • The event.preventDefault() method prevents the form from submitting to the server.
  • The name entered in the input field is retrieved using document.getElementById("name").value, and an alert is displayed with the user's name.
2. Form Validation

You can also perform form validation before submitting the form. Here's an example of checking if the form input is empty:


  form.addEventListener("submit", function(event) {
  const nameInput = document.getElementById("name").value;
  if (nameInput === "") {
    alert("Please enter your name!");
    event.preventDefault();  // Prevent form submission
  }
});

  

Conclusion

In this second part of the DOM Manipulation series, we've taken a deeper dive into how JavaScript interacts with events, styles, and forms. Here's a quick recap of what we've covered:

  • Event handling: Using addEventListener() to listen for events like clicks and keyboard actions.
  • Style manipulation: Changing the appearance of elements dynamically with inline styles or by toggling CSS classes.
  • Forms: Handling user input, preventing default form submissions, and performing form validation.
In the next part of this series, we will explore more advanced topics like creating and removing elements, handling animations, and optimizing DOM manipulation for performance. Stay tuned!

Key Takeaways:

  • Event handling enables interactive and responsive web pages.
  • Style manipulation allows for dynamic changes to the appearance of elements.
  • Form handling is crucial for collecting and validating user input.

By mastering these techniques, you'll be able to create more interactive and user-friendly web pages that respond to user actions in real-time.

Post a Comment

0 Comments