Introduction to JavaScript

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following best describes the primary role of JavaScript in web development?

  • Styling the aesthetic appearance of web page elements.
  • Defining the structure and layout of web pages.
  • Enhancing user interface interactivity and dynamic content. (correct)
  • Managing server-side operations and database interactions.

In what sequence does a web browser typically execute JavaScript code embedded within an HTML document?

  • Parallel execution across all available browser threads.
  • Top-to-bottom order as the browser parses the HTML. (correct)
  • Random order based on script load times.
  • Based on the priority flags set within the JavaScript code.

Which of the following statements accurately describes how JavaScript handles whitespace?

  • Whitespace is significant and alters the functional behavior of the code.
  • JavaScript throws an error when excessive whitespace is detected.
  • JavaScript condenses all whitespace to a single space character.
  • JavaScript generally ignores extra spaces, tabs, and line breaks, using spacing to improve readability. (correct)

Given that JavaScript is case-sensitive, what would be the outcome of declaring two variables named myVariable and MyVariable in the same scope?

<p>JavaScript treats them as distinct variables, each capable of holding different values. (B)</p>
Signup and view all the answers

What is the key distinction between an expression and a statement in JavaScript?

<p>An expression produces a value, whereas a statement performs an action or instruction. (B)</p>
Signup and view all the answers

Which of the following is a valid method for declaring a variable in JavaScript that cannot be reassigned after its initial assignment?

<p>const (C)</p>
Signup and view all the answers

In JavaScript, what is the purpose of the typeof operator?

<p>Determines the data type of a variable. (C)</p>
Signup and view all the answers

What is the expected behavior when a JavaScript function reaches a return statement?

<p>The function immediately stops executing, possibly returning a value to the caller. (A)</p>
Signup and view all the answers

Given the concept of function hoisting in JavaScript, what is the key implication for function declarations?

<p>Function declarations are moved to the top of their scope during compilation, allowing them to be called before they are defined in the code. (D)</p>
Signup and view all the answers

What is meant by 'lexical scope' in JavaScript?

<p>A variable's scope is determined by its placement within the source code. (A)</p>
Signup and view all the answers

The innerText property is used to dynamically insert text into an HTML element using JavaScript.

<p>True (A)</p>
Signup and view all the answers

In JavaScript, whitespace, including extra spaces, tabs, and line breaks, is always significant and affects how the code is interpreted.

<p>False (B)</p>
Signup and view all the answers

In JavaScript, a statement is the same as an expression.

<p>False (B)</p>
Signup and view all the answers

In javascript the const keyword can be used to define a variable, and that variable can be reassigned a new value later in the script.

<p>False (B)</p>
Signup and view all the answers

JavaScript functions must be defined before they are called, and function hoisting will promote the function declaration to the top of the script.

<p>False (B)</p>
Signup and view all the answers

A global variable in JavaScript is accessible only within the function in which it is declared.

<p>False (B)</p>
Signup and view all the answers

JavaScript handles different data types in the same way, eliminating the necessity for type conversion in mathematical operations.

<p>False (B)</p>
Signup and view all the answers

In JavaScript, the parseInt() function converts a string to an integer, stopping the conversion and ignoring alphabetic characters after the numeric part.

<p>True (A)</p>
Signup and view all the answers

In JavaScript, the addition operator (+) can only be used for summing numbers, whereas concatenation of strings uses a different operator.

<p>False (B)</p>
Signup and view all the answers

Relational comparison operators such as >, <, >=, and <= in JavaScript can be used effectively to compare values of different data types, including strings and numbers.

<p>True (A)</p>
Signup and view all the answers

Given the following JavaScript object:

const myObject = { name: "Example", process: function() { return "Running"; } };

Which of the following is the correct way to execute the process method?

<p><code>myObject.process()</code> (A)</p>
Signup and view all the answers

When creating a Date object in JavaScript, which of the following is true regarding the time that is captured by default?

<p>It captures the system's local time without guaranteeing accuracy to UTC or GMT. (A)</p>
Signup and view all the answers

Consider a JavaScript object book with a property title. Which method correctly updates the title from "Old Title" to "New Title"?

<p><code>book[&quot;title&quot;] = &quot;New Title&quot;</code> (B)</p>
Signup and view all the answers

What happens when you use a single numeric argument with the new Array(number) constructor in JavaScript?

<p>It creates an empty array with the specified number of uninitialized slots. (D)</p>
Signup and view all the answers

How do you remove a property from a JavaScript object?

<p>Use the <code>delete</code> operator on the property. (C)</p>
Signup and view all the answers

Which of the following is the correct way to represent a new 'Car' object with properties 'brand' as 'Toyota' and 'year' as 2024 in JavaScript?

<p><code>const car = {brand: 'Toyota', year: 2024};</code> (A)</p>
Signup and view all the answers

What is the primary difference between accessing object properties using dot notation versus bracket notation in JavaScript?

<p>Bracket notation allows property access using variable values, whereas dot notation requires the property name to be a literal. (C)</p>
Signup and view all the answers

Given a JavaScript array numbers = [10, 20, 30, 40, 50], which loop will correctly output each element of the array along with its index?

<p><code>for (let i = 0; i &lt; numbers.length; i++) { console.log(i, numbers[i]); }</code> (D)</p>
Signup and view all the answers

Which of the following statements is true about JavaScript built-in objects like String, Number, and Boolean?

<p>They can be created without the <code>new</code> keyword, as JavaScript recognizes their types automatically. (A)</p>
Signup and view all the answers

Consider a scenario where you need to extract the month from a Date object in JavaScript. Which method should you use, and what does it return?

<p><code>getMonth()</code> which returns the month as an index number (0-11). (B)</p>
Signup and view all the answers

In JavaScript, an object can store multiple, unrelated pieces of data.

<p>False (B)</p>
Signup and view all the answers

Object properties can only be accessed using dot notation.

<p>False (B)</p>
Signup and view all the answers

In JavaScript, objects are static and cannot be modified once they are created.

<p>False (B)</p>
Signup and view all the answers

An array is a built-in JavaScript object that stores multiple values in a single variable.

<p>True (A)</p>
Signup and view all the answers

All built-in JavaScript objects, including Math, inherit from Object.prototype.

<p>True (A)</p>
Signup and view all the answers

If car is an object with a year property, the code car.year = 2025 will always create a new property named year2025 on the car object.

<p>False (B)</p>
Signup and view all the answers

Using new Array(10) creates an array with a single element, the number 10.

<p>False (B)</p>
Signup and view all the answers

JavaScript Date objects represent date, time, and timezone information.

<p>True (A)</p>
Signup and view all the answers

The getMonth() method of a JavaScript Date object returns the month as a number from 1 to 12.

<p>False (B)</p>
Signup and view all the answers

JavaScript objects are assigned properties as a semi-colon separated list of name:value pairs within () parenthesis.

<p>False (B)</p>
Signup and view all the answers

Which of the following is the primary purpose of control structures in JavaScript?

<p>To manage the flow of execution in a program through conditional logic and looping. (A)</p>
Signup and view all the answers

What happens in a JavaScript switch statement when none of the case expressions match the switch expression, and no default case is provided?

<p>The switch statement is skipped entirely, and execution continues with the next statement after the switch block. (D)</p>
Signup and view all the answers

In the context of a JavaScript for loop, what is the role of the 'modifier' expression?

<p>It updates the loop counter variable after each iteration. (B)</p>
Signup and view all the answers

What distinguishes a do...while loop from a while loop in JavaScript?

<p>A <code>do...while</code> loop always executes its code block at least once. (A)</p>
Signup and view all the answers

In JavaScript, how does the break statement affect the execution of a loop?

<p>It terminates the loop entirely, transferring control to the next statement after the loop. (A)</p>
Signup and view all the answers

What is the function of the continue statement within a loop in JavaScript?

<p>To skip the rest of the current iteration and proceed with the next iteration. (D)</p>
Signup and view all the answers

Consider a JavaScript if statement used to check if a user is an administrator: if (isAdmin) { // admin actions }. Which of the following best describes the condition being evaluated?

<p>The code block will execute if <code>isAdmin</code> is truthy. (A)</p>
Signup and view all the answers

How can you include multiple conditions in an if statement in JavaScript?

<p>By using logical operators such as <code>&amp;&amp;</code> (AND) or <code>||</code> (OR) to combine conditions. (A)</p>
Signup and view all the answers

What is the expected output of the following code snippet?

let i = 0;
while (i < 5) {
  if (i === 3) {
    break;
  }
  console.log(i);
  i++;
}

<p>0 1 2 (B)</p>
Signup and view all the answers

What is the primary reason for using the default case in a switch statement?

<p>To specify the code to be executed when none of the <code>case</code> values match the switch expression. (B)</p>
Signup and view all the answers

Control structures primarily manage data storage rather than the sequence of execution in a program.

<p>False (B)</p>
Signup and view all the answers

In JavaScript, an if statement can only execute code if a given condition is false.

<p>False (B)</p>
Signup and view all the answers

Using an else block in conjunction with an if statement provides an alternative execution path when the condition is true.

<p>False (B)</p>
Signup and view all the answers

In a switch statement, the default block is executed when none of the case values match the switch expression.

<p>True (A)</p>
Signup and view all the answers

Omitting a break statement at the end of a case in a switch block prevents the execution of subsequent case blocks.

<p>False (B)</p>
Signup and view all the answers

The getDay() method returns the day of the month as a number.

<p>False (B)</p>
Signup and view all the answers

In a for loop, the modifier statement is executed only once at the beginning of the loop.

<p>False (B)</p>
Signup and view all the answers

Both while loops and for loops are post-test loops, evaluating the condition after executing the statements inside the loop.

<p>False (B)</p>
Signup and view all the answers

A do...while loop is guaranteed to execute its code block at least once, regardless of whether the condition is initially true or false.

<p>True (A)</p>
Signup and view all the answers

The continue statement immediately terminates the loop and transfers control to the statement following the loop.

<p>False (B)</p>
Signup and view all the answers

What does the Window.screen.colorDepth property in JavaScript provide?

<p>The bit value indicating the color range supported by the user's screen. (A)</p>
Signup and view all the answers

Given a webpage with multiple images, how does JavaScript's HTML DOM API allow you to access the second image element?

<p>Using <code>document.images[1]</code>. (C)</p>
Signup and view all the answers

Why might accessing elements via index in component arrays (like document.images[0]) be considered an 'old approach' in modern JavaScript development?

<p>Index positions can change when modifying HTML, leading to errors. (A)</p>
Signup and view all the answers

When using document.write() to add content to a webpage, what is a key consideration regarding its use?

<p>It replaces all existing HTML content if executed after the initial page load. (C)</p>
Signup and view all the answers

If you have a dynamically created <select> element in JavaScript, how can you determine the index of the currently selected option?

<p>By checking the <code>selectedIndex</code> property of the <code>&lt;select&gt;</code> element. (C)</p>
Signup and view all the answers

In JavaScript, what is the primary distinction between using innerHTML and innerText when modifying the content of an HTML element?

<p><code>innerHTML</code> interprets and renders HTML tags, while <code>innerText</code> treats everything as plain text. (B)</p>
Signup and view all the answers

What is the significance of the return value of the window.confirm() method in JavaScript?

<p>It returns <code>true</code> if the user clicks 'OK' and <code>false</code> if the user clicks 'Cancel'. (B)</p>
Signup and view all the answers

In the context of JavaScript events, what is the difference between the 'HTML Event Attributes' method and the addEventListener method for handling events?

<p><code>addEventListener</code> allows registering multiple event listeners for the same event on one element, while HTML Event Attributes do not. (C)</p>
Signup and view all the answers

When a 'keydown' event is triggered in JavaScript, what is the primary information provided by the event object?

<p>The type of event and the element that triggered the event. (A)</p>
Signup and view all the answers

In JavaScript, how do you access all radio buttons or checkboxes that share the same name attribute to determine which one is selected?

<p>Use <code>document.getElementsByName('name')</code> and iterate through the resulting array-like object. (C)</p>
Signup and view all the answers

The DOM organizes a webpage into a hierarchical tree, with components nested under the root object named document.

<p>False (B)</p>
Signup and view all the answers

Using Window.screen.width and Window.screen.height provides the total screen dimensions, including areas potentially obscured by system UI like taskbars.

<p>True (A)</p>
Signup and view all the answers

The property Window.screen.colorDepth specifies the number of bits used to represent the black and white range of each pixel, which affects the displayable color range.

<p>False (B)</p>
Signup and view all the answers

The window.confirm() method presents a dialog box to the user with "OK" and "Cancel" options, returning true if "OK" is selected and false if "Cancel" is selected.

<p>True (A)</p>
Signup and view all the answers

The Document Object Model's (DOM) document object allows direct manipulation of the browser window itself, including its dimensions and location.

<p>False (B)</p>
Signup and view all the answers

The document.images.length property returns the quantity of image elements within the DOM, while document.images[0].src is strictly used to set the image URL.

<p>False (B)</p>
Signup and view all the answers

The modern methods of accessing elements using document.getElementById() are more prone to errors and harder to maintain compared to accessing elements via index in component arrays.

<p>False (B)</p>
Signup and view all the answers

The innerText property is capable of interpreting and rendering HTML tags, making it suitable for inserting formatted text with elements like bold or italics.

<p>False (B)</p>
Signup and view all the answers

Using document.write() to modify the document after the initial page load is a modern and recommended practice for creating dynamic web content.

<p>False (B)</p>
Signup and view all the answers

When handling events in JavaScript, the 'load' event fires exclusively after all content, including images and external resources, has completely finished loading.

<p>True (A)</p>
Signup and view all the answers

Flashcards

What is JavaScript?

A scripting language embedded in web browsers to enhance web page interactivity and responsiveness.

Language Basics

Syntax, keywords, operators and built-in objects in JS.

Where to include Javascript?

The best practice is to place scripts at the end of the section.

Keywords

Words that have a special meaning in the JavaScript language.

Signup and view all the flashcards

Operators

Special characters that perform operations on one or more operands.

Signup and view all the flashcards

Whitespace relevance

Total = 100 + 200 is readable, total=100+200 is less readable.

Signup and view all the flashcards

Variable declaration

Automatically, Using var, Using let, Using const

Signup and view all the flashcards

Data types in JavaScript

String, Number, Boolean, Object, Function, Symbol, null, and undefined.

Signup and view all the flashcards

What is a function?

Block of code designed to perform task, returns a final value.

Signup and view all the flashcards

What is Scope?

Where a variable is accessible: global or local.

Signup and view all the flashcards

Client-side scripting

Enables website interactivity directly in the browser, reducing server reliance.

Signup and view all the flashcards

ECMAScript

JavaScript was standardized as ECMAScript by Ecma International.

Signup and view all the flashcards

Writing to HTML

Dynamically write content into an HTML element.

Signup and view all the flashcards

JavaScript Statements

Series of instructions executed top to bottom by the browser engine.

Signup and view all the flashcards

Statement Components

Words, strings, numbers, booleans, or code that produce a single value.

Signup and view all the flashcards

String Literals

Text enclosed in single ('example') or double quotes ("example").

Signup and view all the flashcards

Variable Values

Containers for storing data that can be changed during script execution.

Signup and view all the flashcards

Expressions

Produce a single value by combining values and operators.

Signup and view all the flashcards

Comments in Javascript

Comments explain code, improving understanding and maintenance.

Signup and view all the flashcards

Loosely Typed Variable

A variable whose data type may change during execution.

Signup and view all the flashcards

What is an Object?

A way to store multiple pieces of related data in a structured format.

Signup and view all the flashcards

Object Attributes (Properties)

Characteristics of an object, like color, brand, and model.

Signup and view all the flashcards

Object Behaviors (Methods)

Actions that an object can perform such as accelerate, start, and stop.

Signup and view all the flashcards

Accessing Object Properties

Reference object property values using dot notation or bracket notation.

Signup and view all the flashcards

Calling Object Methods

Use dot notation to call methods: objectName.methodName()

Signup and view all the flashcards

Extending Objects

You can add, modify, and remove properties from objects.

Signup and view all the flashcards

Constructor Method

Built-in objects have a constructor method, except Math.

Signup and view all the flashcards

Built-in Objects

String, Number, Boolean, Object, Function, Symbol, Date, Array, RegExp, Math, Error

Signup and view all the flashcards

What is an Array?

Stores multiple values in a single variable.

Signup and view all the flashcards

Date Object

Represents date, time, and timezone information.

Signup and view all the flashcards

Objects in JavaScript

Grouping related data and functions into a single unit.

Signup and view all the flashcards

How to create a Date Object

Use the new keyword to declare

Signup and view all the flashcards

getFullYear() Method

Four digit representation for year

Signup and view all the flashcards

getMonth() Method

Indexes the month. (0-11)

Signup and view all the flashcards

getDate()

Specify the day

Signup and view all the flashcards

getDay() Method

The weekday as an index number (0-6)

Signup and view all the flashcards

getHours()

Gets the hour as a number (0-23)

Signup and view all the flashcards

Array Indexes

Values are automatically indexed starting from 0

Signup and view all the flashcards

Control Structures

Control structures determine how a program executes, enabling conditional execution and loops.

Signup and view all the flashcards

if Statement

An if statement checks a condition; code runs if true.

Signup and view all the flashcards

if-else Statement

Extends if to execute code when the condition is false.

Signup and view all the flashcards

switch Statement

Tests multiple conditions with a default case if no match is found

Signup and view all the flashcards

Loop

A structure that repeats a block of code as long as a condition is met.

Signup and view all the flashcards

while loop

Executes code repeatedly while a condition is true, condition tested first.

Signup and view all the flashcards

do-while loop

Executes code block once, then repeats if condition is true, condition checked after.

Signup and view all the flashcards

break Keyword

Exits a loop prematurely based on a condition.

Signup and view all the flashcards

continue Keyword

Skips one loop iteration if condition met, continues with the next.

Signup and view all the flashcards

if Statement Definition

Evaluates a condition; executes code if true.

Signup and view all the flashcards

if...else Extension

Adds an alternative execution path when the condition is false.

Signup and view all the flashcards

switch Statement Function

Checks one case against multiple values, with a default option.

Signup and view all the flashcards

Loop Definition

Repeats until test condition is false.

Signup and view all the flashcards

break Statement Use

Terminates a loop prematurely.

Signup and view all the flashcards

continue Statement Action

Skips an iteration and proceeds with the next.

Signup and view all the flashcards

while Loop Definition

Executes code as long as the condition remains true.

Signup and view all the flashcards

do...while Loop

Executes once before checking condition; then repeats if true.

Signup and view all the flashcards

Document Object Model (DOM)

A hierarchical tree organizing web page components, allowing JavaScript to access and change HTML elements.

Signup and view all the flashcards

window.screen.width

Total screen width in pixels.

Signup and view all the flashcards

window.screen.height

Total screen height in pixels.

Signup and view all the flashcards

window.screen.colorDepth

Bit value indicating color range.

Signup and view all the flashcards

window.alert(message)

Displays alert box with a message and 'OK' button.

Signup and view all the flashcards

window.confirm(message)

Displays a confirmation box with 'OK' and 'Cancel' buttons.

Signup and view all the flashcards

window.prompt(message, defaultValue)

Displays a prompt box with a text input field.

Signup and view all the flashcards

document.title

Retrieves or sets the document's title.

Signup and view all the flashcards

getElementsByClassName()

Returns all elements with a specific class name

Signup and view all the flashcards

appendChild()

Appends the new element inside an existing parent element.

Signup and view all the flashcards

DOM Importance

Enables dynamic content updates and interaction.

Signup and view all the flashcards

Screen Child Object

Provides properties of the user's monitor resolution.

Signup and view all the flashcards

document.domain

Returns the domain name of the document.

Signup and view all the flashcards

document.forms.length

Returns number of elements in document.

Signup and view all the flashcards

getElementById()

Retrieves uniquely identified single element.

Signup and view all the flashcards

innerText

Property of an element returns content between opening/closing tags.

Signup and view all the flashcards

createElement()

Creates a new HTML element dynamically.

Signup and view all the flashcards

setAttribute()

Set the attributes a new HTML element.

Signup and view all the flashcards

Event Handlers

Functions executed when events occur.

Signup and view all the flashcards

Multiple property

Indicates whether multiple options can be selected.

Signup and view all the flashcards

Study Notes

### Meet DOM
- A browser organizes web page components into a hierarchical tree.
- The tree is called the Document Object Model (DOM).
- Each component is nested under the top-level window object.
- JavaScript can access and change HTML document elements using the HTML DOM.
- The DOM enables dynamic webpage changes without reloading.
- It aids JavaScript interaction with HTML and CSS.
- Its essential for creating interactive web applications.
- JavaScript can change HTML elements/attributes/CSS styles in the page.
- Enables JavaScript to remove/add HTML elements/attributes.
- JavaScript can react to all existing HTML events in the page.
- Also lets JavaScript create new HTML events in the page

### Inspect Properties
- The top-level DOM window object has a screen child object.
- The screen child object provides properties that describe user's monitor resolution in pixels.

### Screen Dimensions and Usable Space
- The overall screen size can be accessed through Window.screen.width (total width in pixels) and Window.screen.height (total height in pixels).
- Usable screen space, excluding system UI elements, is found using Window.screen.availWidth (available width) and Window.screen.availHeight (available height).
- These properties help optimize layout design to ensure content fits in the user's available screen area.

### Color Depth Information
- Window.screen.colorDepth represents the bit value for color range.
- Common values include 8-bit (256 colors), 16-bit (65,536 colors), 24-bit (millions of colors), and 32-bit (billions of colors).
- 8-bit = low color
- 16-bit = high color
- 24-bit = true color
- 32-bit = deep color

### Show Dialogs
- The top-level DOM window object provides three methods for JavaScript to display dialog messages.
- A simple warning message can be displayed via window.alert(message).
- A confirmation box with "OK" and "Cancel" buttons is displayed via window.confirm(message), returning true for "OK" and false for "Cancel".
- The function window.prompt(message, defaultValue) displays a prompt box with a text input field, an "OK" button (returns the input value), and a "Cancel" button (returns null).

### Extract Info
- The document object is a child of the window object.
- Provides access to and allows manipulation of the HTML document.
- Dynamically updating web pages is useful.
- Commonly utilized in JavaScript for dynamic page interactions.
- The document object provides access to the page title (document.title), current URL (document.URL), domain name (document.domain), last modified date (document.lastModified), and referrer URL (document.referrer).
- document.title retrieves or sets the page title.
- document.URL provides the full URL of the current document.
- document.domain retrieves the domain name of the document, similar to location.host.

### Address Arrays
- The document object has child objects like forms, images, links, styleSheets, and scripts.
- Each object is represented as an array corresponding to elements in the HTML document.
- The number of each object in the document can be returned via:
  - document.forms.length (number of forms)
  - document.images.length (number of images)
  - document.links.length (number of links)
  - document.scripts.length (number of scripts)

### Address Array
- To access the first image (HTML tag) in the document body: document.images[0].
- The URL can be referenced using document.images[0].src.
- Dynamically replacing the old URL with a new URL in script is possible.

### Address Elements
- Error-prone: Accessing elements via index in component arrays can lead to errors because index positions change when modifying HTML.
- Solution is tedious and hard to maintain due to complexity in dynamic pages.
- Modern methods:
  - Accessing element by ID.
  - Accessing element by tag name.
  - Accessing element by class name.

### Accessing element by ID
- Retrieves a single element by its id.
- Best for unique elements like headers, buttons, or sections.

### Accessing element by tag name
- Retrieves all elements with the given tag name.
- Returns an HTMLCollection (array-like structure).

### Accessing element by class name
- Retrieves all elements with a specific class.
- Returns an HTMLCollection.
- Applies styles or modifications to multiple elements at once.

### Write Content
- Methods to Write Content in the DOM:
  - Insert or Change HTML Content (innerHTML). 
  - Insert or Change Text (No HTML).
  - Writing Content Directly to the Page (document.write).

### Insert or Change HTML Content
- Allows setting or retrieving an element's HTML content.
- Supports text and HTML elements.

### Insert or Change Text
- Returns only the content between an elements tags.
- Used to sets or retrieves only text content.
- Ignores HTML tags, treating them as plain text

### Writing Content Directly to the Page
- Writes directly into the document body.
- Replaces all existing HTML content if executed after page load.
- Not recommended for modern web development.
- Used mainly for testing or when loading a new page dynamically.
- Creates an HTML element dynamically by using createElement(tagName)
- Takes the tag name as an argument
- Content can be added using .innerHTML or .innerText
- Appends the new element inside an existing parent.
- Places the new element at the end of the parent's content
- Adds attributes new attributes dynamically to DOM elements
- Takes two arguments" Attribute and Value

### Events
- The DOM allows JavaScript to react to "events" that occur on a web page. Functions are executed when a particular event happens.
- These functions are known as "event-handlers", and can react to events such as:
  - load: Page loaded.
  - click: User clicks a mouse button.
  - keydown: User presses a keyboard key.
  - change: User modifies an input field.
  - submit: User submits an HTML form.
- 2 Main components to consider:
  - The Event Itself
  - The Reaction

### The Event Itself
- What happens that you want to respond to like:
  - load
  - click
  - mousemove
  - keydown, keyup
  - submit

### The Reaction
- This is the function you define to react to the event
- For example, you might:
  - Change the style (e.g., make a button red)
  - Add or remove text/content from the page
  - Send data to the server
  - Show/hide an element
- two main ways to use or handle events:
  - HTML Event Attributes (Inline Method)
  - JavaScript (addEventListener Method)

### HTML Event Attributes (Inline Method)
- You directly add the event in the HTML element using an attribute like onclick, onmouseover, etc.

### JavaScript (addEventListener Method)
- It allows you to register a function to be executed when a specific event occurs on a specific element.
- This is the recommended way, especially in modern development.

### Load Events
- Fired when the entire page has completely loaded.
- The browser waits for loading everything before triggering the event.
- When responding to the load event in JavaScript, there are two main ways to define the event handler:
  - Using the window.onload Property.
  -  Using add an event listener.

### Mouse Events
- Triggered when the user interacts with the mouse (or similar input device) over an element on the page
- click: Fired when the user clicks on an element (press + release)
- dblclick: Fired when the user double-clicks.
- mouseover: When the pointer enters an element.
- mouseout: When the pointer leaves an element.

### Events Values
- An event object contains information about the event that occurred, such as:
  - What type of event it was (e.g. click, keydown)
  - Where it happened (mouse coordinates)
  - Which key was pressed
  - Which element triggered the event

### Check Boxes
- Checkboxes and Radio Buttons

### Checkboxes
- Allow users to select multiple options.
- Each checkbox is independent.

### Radio Buttons
- Allow users to select only one option from a group.
  - All buttons in a group share the same name attribute.
- Grouping Behavior and JavaScript Access
  - Grouping by name
    - Checkboxes and radio buttons are grouped by the same name.
  - Javascript access
    - You can access the group using JavaScript
 - The result is an array-like object, and you can:
    - Loop through it.
    - Access each element using an index.
    - Read or assign the .checked property.
-  The .checked Property is a Boolean property on both checkboxes and radio buttons.
- True = selected, false= not selected

### Select options
- The &lt;select&gt; element is used in HTML to create a drop-down list of options that a user can choose from.
- You can interact with a &lt;select&gt; element in JavaScript using several useful properties:
  - selectedIndex = Returns or sets the index of the selected option (starts at 0).
  - value = Returns or sets the value of the selected option.
  - options = Returns a collection (array-like) of all &lt;option&gt; elements inside &lt;select&gt;.
  - length = Returns the number of options in the drop-down.
  - multiple = A Boolean that indicates whether multiple options can be selected.

### Summary of Script Flow Management
- The `if` keyword performs the basic conditional test to test a condition for a boolean true or false value.
- An alternative branch to the basic conditional test uses the `else` keyword to extend an `if` statement.
- `switch` statement tests a large number of conditions for a boolean true or false value.
- In a `switch` block, each `case` statement must end with the `break` keyword to exit upon finding a match.
- A `switch` block may contain a final `default` statement to execute when no match has been found.
- A `for` loop specifies an initializer, a condition to be tested for a boolean true or false value, and a modifier, and the modifier must enable the tested condition to become false at some point to exit the loop.
- The `while` and `for` loops evaluate a test condition before any statements are executed.
- The `do while` loop evaluates a test condition after its statements have been executed.
- The `break` keyword exits from a loop when a specified condition is encountered.
- The `continue` keyword skips a single iteration of a loop when a specified condition is encountered.
- The document object has title, URL, domain, lastModified, and referrer properties that describe that document.
- The document object has forms, images, links, styleSheets, and scripts child objects that are arrays of document components.
- The document object has getElementById( ), getElementsByTagName(), and getElementsByClassName( ) methods that can be used to reference HTML elements.
- The innerHTML and innerText properties of the document object can be used to write content into existing elements.
- The document object has createElement( ), appendChild( ), and setAttribute( ) methods that can add content to a document.
- The DOM allows JavaScript to react to events such as load, click, keydown, change, and submit in response to user actions.
- Event-handler functions can be assigned to an object property or specified by the addEventListener( ) method.
- An event object can be passed to an event-handler function and the event can be identified by its event.type property.
- Radio and checkbox button objects have a checked boolean property, which is only true when the button is selected.
- A selection list object has a selectedIndex property, which contains the index number of the currently selected options[ ] array element.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

JavaScript History and Versions
39 questions
JavaScript Fundamentals and Web Standards
24 questions
Introduction to JavaScript
40 questions
Use Quizgecko on...
Browser
Browser