0% found this document useful (0 votes)
33 views5 pages

Day - 6 Conditionals, Loops, Events

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views5 pages

Day - 6 Conditionals, Loops, Events

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Conditionals, Loops, and Events

1. Conditionals

Conditionals allow your program to make decisions based on whether a condition is true or false.

 If Statement: Executes a block of code if a specified condition is true.

if (condition) {

// code to execute

 Else Statement: Executes a block of code if the condition in the if statement is false.

if (condition) {

// code if true

} else {

// code if false

 Else If Statement: Executes a block of code if the if condition is false and the else if condition
is true.

if (condition1) {

// code if true

} else if (condition2) {

// code if condition2 is true

 Switch Statement: Compares a value to multiple possible cases and executes the
corresponding code block.

switch (value) {

case 1:

// code

break;

case 2:

// code

break;

default:

// code if no case matches


}

Example:

let score = 85;

if (score >= 90) {

console.log("Grade A");

} else if (score >= 80) {

console.log("Grade B");

} else {

console.log("Grade C");

2. Loops

Loops are used to repeatedly execute a block of code as long as a specified condition is true.

 For Loop: Executes a block of code a set number of times.

for (let i = 0; i < 5; i++) {

console.log(i);

 While Loop: Repeats a block of code as long as the condition is true.

let i = 0;

while (i < 5) {

console.log(i);

i++;

 For Each Loop: Iterates over array elements.

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(num => {

console.log(num);

});

3. Events

Events in JavaScript enable you to interact with users by responding to various actions, such as clicks,
key presses, mouse movements, etc. These interactions are captured through event listeners, which
listen for specific events on HTML elements and then trigger functions or actions when those events
occur.
1. What is an Event?

An event in JavaScript refers to any action or occurrence that the browser detects, like a user clicking
a button, typing in a text field, or moving the mouse. These events are used to trigger actions or
functions that respond to those occurrences. Examples include:

 Click: When the user clicks on an element.

 Mouseover: When the mouse pointer hovers over an element.

 Keydown: When a key is pressed down on the keyboard.

 Submit: When a form is submitted.

2. Event Listeners

An event listener is a JavaScript function that listens for specific events and executes a function when
that event occurs. You can attach event listeners to HTML elements using methods like
addEventListener(), which is the standard way to handle events in JavaScript.

Syntax for addEventListener():

element.addEventListener(event, function, useCapture);

 event: The type of event to listen for (like 'click', 'keydown', etc.).

 function: The function to be called when the event occurs.

 useCapture: Optional. A Boolean value that determines whether the event should be
handled during the capturing phase or the bubbling phase (default is false, meaning bubbling
phase).

Example: Handling a Button Click

Here is a simple example where an event listener is used to show an alert when a button is clicked:

document.getElementById("button").addEventListener("click", function() {

alert("Button clicked!");

});

 Explanation: When the user clicks the button with the ID "button", an alert will be displayed
with the message "Button clicked!".

3. Commonly Used Events

- Click (click):

Occurs when the user clicks on an element (like a button or a link).

document.getElementById("submitButton").addEventListener("click", function() {

console.log("Form submitted!");

});
- Mouseover (mouseover):

Triggered when the mouse pointer enters the boundaries of an element.

document.getElementById("hoverElement").addEventListener("mouseover", function() {

console.log("Mouse is over the element!");

});

- Keydown (keydown):

Occurs when a key is pressed down on the keyboard.

document.getElementById("textInput").addEventListener("keydown", function(event) {

console.log("Key pressed: " + event.key);

});

- Submit (submit):

Triggered when a form is submitted. Typically used to validate data before submission.

document.getElementById("myForm").addEventListener("submit", function(event) {

event.preventDefault(); // Prevents form from submitting for validation

console.log("Form submitted!");

});

4. Event Propagation: Bubbling and Capturing

Event propagation defines the order in which events are handled in the DOM. It consists of two
phases:

 Bubbling phase: The event starts from the target element and bubbles up to the root of the
document.

 Capturing phase: The event starts from the root of the document and moves down to the
target element.

By default, event listeners are triggered during the bubbling phase. However, you can change the
phase in which the event listener is triggered by setting the third parameter (useCapture) to true for
the capturing phase.

Example:

document.getElementById("parent").addEventListener("click", function() {

console.log("Parent clicked!");

}, true); // Capturing phase

document.getElementById("child").addEventListener("click", function() {

console.log("Child clicked!");
});

In the above example, the parent's event listener will be triggered first during the capturing phase,
followed by the child's event listener.

5. Removing Event Listeners

You can also remove event listeners if you no longer need to handle events. This can be done using
the removeEventListener() method.

function onClick() {

alert("Button clicked!");

let button = document.getElementById("button");

button.addEventListener("click", onClick);

// Later, remove the event listener

button.removeEventListener("click", onClick);

6. Event Object

When an event occurs, an event object is automatically passed to the callback function. This object
contains useful information about the event, such as which element was clicked, the mouse
coordinates, the key pressed, etc.

For example:

document.getElementById("button").addEventListener("click", function(event) {

console.log(event.target); // The element that triggered the event

console.log(event.type); // The type of the event, e.g., 'click'

});

In summary, events allow for interaction with the browser, and event listeners are a powerful way to
respond to user actions and enhance the interactivity of web pages.

You might also like