JavaScript Events

Learn how to handle events in JavaScript to create interactive web pages.

Introduction to Events

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so your code can respond to them.

Common Event Types:

  • Mouse events (click, dblclick, mouseover)
  • Keyboard events (keydown, keyup)
  • Form events (submit, change)
  • Window events (load, resize)

The onclick Event

Used to trigger a function when an element is clicked:


<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
  alert("Hello from CodingRider!");
}
</script>
            

Using addEventListener()

The modern way to attach events:


let btn = document.getElementById("myBtn");

btn.addEventListener("click", function() {
  alert("Button clicked!");
});
            

Input Events

Respond to user typing:


<input type="text" id="username">

<script>
document.getElementById("username").addEventListener("input", function(e) {
  console.log("Typed:", e.target.value);
});
</script>
            

Form Submission

Prevent a form from submitting and handle it with JavaScript:


document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault(); // stop page reload
  alert("Form submitted via JS!");
});
            

Mouse Events

  • click
  • dblclick
  • mouseover
  • mouseout

Best Practices

  • Use addEventListener for cleaner code
  • Separate logic from HTML (avoid inline JS if possible)
  • Always use e.preventDefault() for form control

Practice Task

Create a button that, when clicked, updates a paragraph with a message:


<button id="updateBtn">Update Text</button>
<p id="message"></p>

<script>
document.getElementById("updateBtn").addEventListener("click", function() {
  document.getElementById("message").textContent = "Updated successfully!";
});
</script>