Working with Events & DOM Traversing in JavaScript

Payal PorwalPayal Porwal
5 min read

Working with Events in JavaScript

Events in JavaScript allow developers to make web pages interactive by responding to user actions like clicks, mouse movements, or form inputs.

1. addEventListener()

What It Does:

  • addEventListener() is used to attach an event handler to an element without overwriting existing event listeners.

Syntax:

element.addEventListener("event", functionName);

Real-Life Examples:

  1. Handling a Button Click

     <button id="clickButton">Click Me</button>
     <script>
       document.getElementById("clickButton").addEventListener("click", function() {
         alert("Button Clicked!");
       });
     </script>
    
  2. Detecting Key Presses in an Input Field

     <input type="text" id="textInput" placeholder="Type something...">
     <p id="output"></p>
     <script>
       document.getElementById("textInput").addEventListener("keyup", function(event) {
         document.getElementById("output").innerText = "You typed: " + event.target.value;
       });
     </script>
    
  3. Changing Background Color on Mouse Move

     <div id="colorBox" style="width:100px;height:100px;background:gray;"></div>
     <script>
       document.getElementById("colorBox").addEventListener("mousemove", function() {
         this.style.backgroundColor = "lightblue";
       });
     </script>
    

2. Common Event Attributes (onclick, onmouseover, onchange, etc.)

What They Do:

  • These attributes define what happens when a specific event occurs.

  • Common events include:

    • onclick: Triggers when an element is clicked.

    • onmouseover: Fires when the mouse hovers over an element.

    • onchange: Fires when an input value changes.

Real-Life Examples:

  1. Toggling an Element's Visibility (onclick)

     <p id="text">This is a paragraph.</p>
     <button onclick="toggleText()">Show/Hide</button>
     <script>
       function toggleText() {
         let text = document.getElementById("text");
         text.style.display = text.style.display === "none" ? "block" : "none";
       }
     </script>
    
  2. Hover Effect (onmouseover)

     <button onmouseover="changeText(this)" onmouseout="resetText(this)">Hover Me</button>
     <script>
       function changeText(element) {
         element.innerText = "Hovered!";
       }
       function resetText(element) {
         element.innerText = "Hover Me";
       }
     </script>
    
  3. Updating a Live Preview (onchange)

     <input type="text" id="nameInput" onchange="updatePreview()">
     <p>Preview: <span id="namePreview"></span></p>
     <script>
       function updatePreview() {
         document.getElementById("namePreview").innerText = document.getElementById("nameInput").value;
       }
     </script>
    

3. Event Object (event.target, event.preventDefault())

What It Does:

  • event.target: Refers to the element that triggered the event.

  • event.preventDefault(): Prevents the default behavior of an element (e.g., stopping form submission).

Syntax:

document.addEventListener("event", function(event) {
  event.target; // Reference to the element
  event.preventDefault(); // Prevent default action
});

Real-Life Examples:

  1. Detecting Clicked Element (event.target)

     <button id="btn1">Button 1</button>
     <button id="btn2">Button 2</button>
     <p id="result"></p>
     <script>
       document.addEventListener("click", function(event) {
         document.getElementById("result").innerText = "You clicked: " + event.target.innerText;
       });
     </script>
    
  2. Preventing Default Form Submission (event.preventDefault())

     <form id="myForm">
       <input type="text" id="username" required>
       <button type="submit">Submit</button>
     </form>
     <script>
       document.getElementById("myForm").addEventListener("submit", function(event) {
         event.preventDefault();
         alert("Form submission prevented!");
       });
     </script>
    
  3. Preventing Default Link Behavior (event.preventDefault())

     <a href="https://example.com" id="myLink">Click Me</a>
     <script>
       document.getElementById("myLink").addEventListener("click", function(event) {
         event.preventDefault();
         alert("Link click prevented!");
       });
     </script>
    

Conclusion

  • addEventListener() is the preferred way to attach event listeners.

  • Inline event handlers like onclick are simple but less flexible.

  • The event object provides useful properties like event.target and event.preventDefault().

  • Understanding events allows for dynamic, interactive web applications.

By practicing these examples, you'll gain confidence in handling events effectively! 🚀

DOM Traversing in JavaScript

DOM (Document Object Model) Traversing allows us to navigate through elements in a webpage structure by moving between parents, children, and siblings.


1. parentNode & parentElement

What They Do:

  • parentNode: Returns the parent node of an element (could be an element, document, or text node).

  • parentElement: Returns only the parent element (if the parent is not an element, it returns null).

Syntax:

let parent = element.parentNode;
let parentEl = element.parentElement;

Real-Life Examples:

  1. Getting the Parent of an Element

     <div id="parent">
       <p id="child">Hello, World!</p>
     </div>
     <script>
       let child = document.getElementById("child");
       console.log(child.parentNode); // Logs <div id="parent">
     </script>
    
  2. Changing the Parent Element's Background Color

     <div id="box" style="padding:20px; border:2px solid black;">
       <button id="btn">Click Me</button>
     </div>
     <script>
       document.getElementById("btn").addEventListener("click", function() {
         this.parentElement.style.backgroundColor = "lightblue";
       });
     </script>
    
  3. Removing an Element Using Parent Node

     <div id="container">
       <p id="para">This is a paragraph.</p>
       <button id="removeBtn">Remove Paragraph</button>
     </div>
     <script>
       document.getElementById("removeBtn").addEventListener("click", function() {
         let para = document.getElementById("para");
         para.parentNode.removeChild(para);
       });
     </script>
    

2. childNodes & children

What They Do:

  • childNodes: Returns all child nodes, including text nodes (whitespace between elements counts as a node).

  • children: Returns only child elements (ignores text nodes).

Syntax:

let nodes = element.childNodes;
let elements = element.children;

Real-Life Examples:

  1. Counting Child Elements

     <ul id="list">
       <li>Item 1</li>
       <li>Item 2</li>
       <li>Item 3</li>
     </ul>
     <script>
       let list = document.getElementById("list");
       console.log("Total children: ", list.children.length); // Outputs 3
     </script>
    
  2. Changing the First Child's Color

     <div id="container">
       <p>First Paragraph</p>
       <p>Second Paragraph</p>
     </div>
     <script>
       let container = document.getElementById("container");
       container.children[0].style.color = "red"; // First paragraph turns red
     </script>
    
  3. Looping Through Child Nodes

     <ul id="menu">
       <li>Home</li>
       <li>About</li>
       <li>Contact</li>
     </ul>
     <script>
       let menu = document.getElementById("menu");
       for (let child of menu.children) {
         console.log(child.innerText); // Logs each menu item text
       }
     </script>
    

3. nextElementSibling & previousElementSibling

What They Do:

  • nextElementSibling: Returns the next sibling element.

  • previousElementSibling: Returns the previous sibling element.

Syntax:

let next = element.nextElementSibling;
let prev = element.previousElementSibling;

Real-Life Examples:

  1. Highlighting the Next Sibling Element

     <p id="para1">First Paragraph</p>
     <p id="para2">Second Paragraph</p>
     <script>
       let firstPara = document.getElementById("para1");
       firstPara.nextElementSibling.style.backgroundColor = "yellow";
     </script>
    
  2. Moving to the Previous Element

     <button id="btn1">Button 1</button>
     <button id="btn2">Button 2</button>
     <script>
       let secondButton = document.getElementById("btn2");
       console.log(secondButton.previousElementSibling.innerText); // Logs "Button 1"
     </script>
    
  3. Toggling Visibility of the Next Sibling

     <button id="toggle">Toggle Next</button>
     <p id="message">This is a message.</p>
     <script>
       document.getElementById("toggle").addEventListener("click", function() {
         let next = this.nextElementSibling;
         next.style.display = next.style.display === "none" ? "block" : "none";
       });
     </script>
    

Conclusion

  • parentNode and parentElement allow moving upwards in the DOM.

  • childNodes retrieves all child nodes (including whitespace), whereas children returns only element nodes.

  • nextElementSibling and previousElementSibling help navigate between sibling elements.

  • These methods are useful for dynamically manipulating the DOM structure.

By practicing these concepts, you can efficiently navigate and manipulate the DOM for interactive web applications! 🚀

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟