Module 2 | Day 8

Day 8: JavaScript Functions and Events

Day 8: JavaScript Functions and Events

Overview

Today, we will learn about functions and events in JavaScript. These concepts are crucial for making your web pages interactive and functional.

JavaScript Functions

Functions are blocks of code designed to perform a particular task. They are executed when they are called (invoked).

Defining a Function

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).


function myFunction() {
  console.log("Hello World!");
}
    

Calling a Function

After defining a function, you can call it by using its name followed by parentheses.


myFunction(); // Calls the function
    

Function Parameters and Arguments

Functions can take parameters. Parameters are listed inside the parentheses in the function definition. Arguments are the values received by the function when it is called.


function greet(name) {
  console.log("Hello " + name);
}

greet("Alice"); // Hello Alice
greet("Bob"); // Hello Bob
    

JavaScript Events

Events are actions that happen in the browser, such as when a user clicks a button, hovers over an element, or submits a form. JavaScript can be used to detect and respond to these events.

Event Listeners

An event listener is a procedure in JavaScript that waits for an event to occur. Here’s how to add an event listener:


document.getElementById("myButton").addEventListener("click", function() {
  alert("Button was clicked!");
});
    

Common Events

Here are some common events you might encounter:

  • click: When an element is clicked.
  • mouseover: When the mouse pointer is moved onto an element.
  • mouseout: When the mouse pointer is moved out of an element.
  • keydown: When a keyboard key is pressed down.
  • submit: When a form is submitted.

Practice Exercise

Try creating a simple JavaScript script that does the following:

  • Defines a function that logs a message to the console.
  • Adds an event listener to a button that calls the function when clicked.

// Your code here
function showMessage() {
  console.log("Button clicked!");
}

document.getElementById("myButton").addEventListener("click", showMessage);
        

Summary

In today's lesson, we covered JavaScript functions and events. You learned how to define and call functions, pass parameters, and handle events to make your web pages interactive.

Next Module: JavaScript DOM Manipulation

In the next lesson, we will explore how to manipulate the DOM (Document Object Model) using JavaScript to dynamically update the content and structure of your web pages. Stay tuned for more exciting JavaScript techniques!