Lecture 13: JavaScript Functions & Event Handling

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-02-16

Lecture 13

JavaScript Functions & Event Handling

Week 4 | Unit II: JavaScript Functions & Events
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Write reusable JavaScript functions
  • Distinguish parameters and arguments
  • Understand function return values
  • Handle browser events with listeners
  • Use the event object in interactions

Why Functions Matter


Functions help avoid repeated code

Functions make code easier to test and debug

Functions improve readability and maintenance

function greet(name) {
  return `Hello, ${name}`;
}

Function Declaration vs Expression


function add(a, b) {
  return a + b;
}

const multiply = function(a, b) {
  return a * b;
};

const square = x => x * x;

add is declared; multiply is stored in a variable; square uses arrow syntax.

Parameters, Arguments, Return


function calculateTotal(price, taxRate) {
  const tax = price * taxRate;
  const total = price + tax;
  return total;
}

const bill = calculateTotal(1000, 0.18);
  • Parameters: price, taxRate
  • Arguments: 1000, 0.18
  • Return value: final result from function

What Are Events?


An event is an action in the browser:

  • user clicks a button
  • user types in an input
  • page is loaded
  • form is submitted
button.addEventListener("click", () => {
  console.log("Clicked");
});

Common DOM Events


element.addEventListener("click", handleClick);
element.addEventListener("change", handleChange);
element.addEventListener("input", handleInput);
form.addEventListener("submit", handleSubmit);
window.addEventListener("load", initPage);

Pick event type based on user interaction you want to capture.

Using the Event Object


form.addEventListener("submit", function(event) {
  event.preventDefault();
  console.log(event.type);
  console.log(event.target);
  console.log("Form submission intercepted");
});
  • preventDefault() stops default behavior
  • target gives the source element

Interactive Counter Demo


<button id="incBtn">Increase</button>
<p id="count">0</p>
let value = 0;
document.getElementById("incBtn").addEventListener("click", () => {
  value++;
  document.getElementById("count").textContent = value;
});

Live Classroom Demo: Functions & Events


Use this interactive page during class to demonstrate:

  • Function declaration and return values
  • Parameters and arguments with real input
  • click, input, and submit events
  • event.preventDefault() in form handling
  • Dynamic DOM updates based on function output

Alternative site path: /html/demos/lecture-13-demo.html

Best Practices


  • Keep functions short and focused
  • Use descriptive names like validateEmail()
  • Avoid inline JS in HTML when possible
  • Prefer addEventListener over old event attributes
  • Handle errors and invalid input safely

Questions?

Next: Lecture 14 - Conditions & Looping