0% found this document useful (0 votes)
0 views

CourseNotes_JavaScript Essential Training 2017

The document provides an overview of the 'JavaScript Essential Training' course, detailing its focus on JavaScript as a key web scripting language and its evolution towards dynamic web interfaces. It covers fundamental concepts such as variables, data types, functions, and advanced topics like closures and DOM manipulation through practical examples. The course is structured into chapters that progressively build understanding through mini-projects and practical exercises.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

CourseNotes_JavaScript Essential Training 2017

The document provides an overview of the 'JavaScript Essential Training' course, detailing its focus on JavaScript as a key web scripting language and its evolution towards dynamic web interfaces. It covers fundamental concepts such as variables, data types, functions, and advanced topics like closures and DOM manipulation through practical examples. The course is structured into chapters that progressively build understanding through mini-projects and practical exercises.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 26

Course Title: JavaScript Essential Training (2017)

Description: JavaScript is a scripting language of the web. As the web evolves from
a static to a dynamic environment, technology focus is shifting from static markup
and styling—frequently handled by content management systems or automated scripts—
to dynamic interfaces and advanced interaction. Once seen as optional, JavaScript
is now becoming an integral part of the web, infusing every layer with its script.
Through practical examples and mini-projects, this course helps you build your
understanding of JavaScript piece by piece, from core principles like variables,
data types, conditionals, and functions through advanced topics including loops,
closures, and DOM scripting. Along the way, you will also be introduced to some ES6
and the basics of JavaScript libraries.

***********************************************
Chapter: 1. JavaScript: An Introduction
***********************************************

-----------------------------------------------
Video: What is JavaScript?
-----------------------------------------------
Note Time: Note Text:

0:00:03 JavaScript is a programming language used to create dynamic and


interactive content on websites.

***********************************************
Chapter: 2. The Basics
***********************************************

-----------------------------------------------
Video: Add inline JavaScript to a HTML document
-----------------------------------------------
Note Time: Note Text:

0:01:40 Purpose: Inline JavaScript is used to run scripts directly


within an HTML file.
Script Tag: Use the <script> tag to wrap your JavaScript code.
Placement:
In the <head>: Runs before the page content is loaded.
After the <body>: Runs after the page content is loaded.

-----------------------------------------------
Video: Add JavaScript in an external file
-----------------------------------------------
Note Time: Note Text:

0:00:01 External javascipt: <script src="script.js" defer></script>


The defer attribute ensures the script loads after the HTML has finished loading.

-----------------------------------------------
Video: How to write JavaScript: A crash course
-----------------------------------------------
Note Time: Note Text:
0:01:49 Comments:Single-line comments start with //, and multi-line
comments are enclosed in /* ... */.

0:02:27 JavaScript ignores extra spaces, tabs, and newlines.

***********************************************
Chapter: 3. Working with data
***********************************************

-----------------------------------------------
Video: Variables: The catch-all containers of JavaScript
-----------------------------------------------
Note Time: Note Text:

0:00:17 Right Away, Asynchronous, and Deferred loading.

Correct

These three loading methods have helped JavaScript evolve from having to put the
script at the end of the code.

0:02:00 What is a Variable?

A variable is like a container that holds data.

0:02:51 Creating Variable : var a = 10;

-----------------------------------------------
Video: Data types in JavaScript
-----------------------------------------------
Note Time: Note Text:

0:00:02 Type Checking: You can check the data type of a variable using
the typeof operator:
javascript
var num = 42;
console.log(typeof num); // Outputs: "number"

0:00:02 Special Note: If you need to include quotes inside a string, you
can use a backslash (\) to escape them:
var quote = "He said, \"Hello!\"";

0:00:02 String: var name = "John Doe"; // using double quotes


var greeting = 'Hello, World!'; // using single quotes

-----------------------------------------------
Video: Arithmetic operators and math
-----------------------------------------------
Note Time: Note Text:

0:00:00 Multiplication and division have higher precedence than addition


and subtraction. For example:
javascript
let result = a + b * c; // b * c is calculated first, then a is added
-----------------------------------------------
Video: Working with strings and numbers
-----------------------------------------------
Note Time: Note Text:

0:00:00 var strNum = "42.7";


var intNum = parseInt(strNum); // Converts string to integer (42)

0:00:00 var num = 456;


var str = String(num); // Converts number to string

0:00:00 var strNum = "123";


var num = Number(strNum); // Converts string to number

0:00:00 javascript
var a = 4;
var b = "5";
var result = a + Number(b); // Result: 9

0:00:00 javascript
var a = 4;
var b = "hello";
var result = a - b; // Result: NaN

Here, JavaScript cannot convert "hello" to a number, so the result is NaN.

0:00:00 These operators (-, *, /) will attempt to convert strings to


numbers
var a = 4;
var b = "5";
var result = a - b; // Result: -1
var result = a * b; // Result: 20
var result = a / b; // Result: 0.8

0:00:00 javascript
var a = 4;
var b = "5";
var sum = a + b; // Result: "45"

Here, a (number) and b (string) are combined into a single string "45".

-----------------------------------------------
Video: Conditional statements and logic
-----------------------------------------------
Note Time: Note Text:

0:01:12 Triple Equals (===): Checks if two values are exactly the same
type and value.

-----------------------------------------------
Video: Arrays
-----------------------------------------------
Note Time: Note Text:

0:00:06 Creating the box (array):


javascript
var pens = ["red", "blue", "green", "orange"];

Getting a pen from the box:


javascript
var firstPen = pens[0]; // "red"

Changing a pen's color:


javascript
pens[3] = "purple"; // Changes "orange" to "purple"

Mixing items in the box:


javascript
var mixedItems = ["pen", 10, true, 3.14, "notebook"];

-----------------------------------------------
Video: Properties and methods in arrays
-----------------------------------------------
Note Time: Note Text:

0:04:41 reverse(): Reverses the order of items in the array.


javascript
pens.reverse(); // ["orange", "green", "blue", "red"]

shift(): Removes the first item of the array.


javascript
pens.shift(); // ["blue", "green", "orange"]

unshift(item): Adds a new item to the beginning of the array.


javascript
pens.unshift("purple"); // ["purple", "red", "blue", "green", "orange"]

pop(): Removes the last item of the array.


javascript
pens.pop(); // ["red", "blue", "green"]

push(item): Adds a new item to the end of the array.


javascript
pens.push("pink"); // ["red", "blue", "green", "orange", "pink"]

splice(index, number): Removes items from the middle of the array.


javascript
pens.splice(2, 1); // Removes "green", resulting in ["red", "blue", "orange"]

slice(start, end): Creates a new array by copying a part of the original array.
javascript
var newPens = pens.slice(1, 3); // ["blue", "green"]

indexOf(item): Finds the index of a specific item.


javascript
var index = pens.indexOf("orange"); // 3

join(separator): Combines all items into a single string, separated by a specified


character.
javascript
var penString = pens.join(", "); // "red, blue, green, orange"
***********************************************
Chapter: 4. Functions and Objects
***********************************************

-----------------------------------------------
Video: Functions in JavaScript
-----------------------------------------------
Note Time: Note Text:

0:02:50 Types of Functions


Named Functions: These are declared with a name and can be called anywhere in the
script after their definition.
function sayHello() {
console.log("Hello!");
}
sayHello(); // Calls the function

-----------------------------------------------
Video: Build a basic function
-----------------------------------------------
Note Time: Note Text:

0:00:49 Immediately Invoked Function Expressions (IIFE): These are


anonymous functions that run immediately after they are defined, often used to
create a new scope.
(function() {
console.log("This runs immediately!");
})();

0:00:49 Anonymous Functions: These functions do not have a name and are
often used as callbacks, especially in event handling or when passed as arguments
to other functions.
const greet = function() {
console.log("Hi there!");
};
greet(); // Calls the function

-----------------------------------------------
Video: Anonymous functions
-----------------------------------------------
Note Time: Note Text:

0:00:02 Anonymous Functions are useful for quick, one-time tasks or when
you don't need to reuse the function elsewhere.

-----------------------------------------------
Video: Immediately invoked functional expressions
-----------------------------------------------
Note Time: Note Text:

0:02:16 Invoked Functional Expressions (IIFEs)


What is an IIFE?

An IIFE is a function that runs as soon as it is defined.


javascript
(function() {
// Code goes here
})();

-----------------------------------------------
Video: Variable scope
-----------------------------------------------
Note Time: Note Text:

0:00:01 What is Variable Scope?

Variable scope determines where in your code a variable can be used.

-----------------------------------------------
Video: ES2015: let and const
-----------------------------------------------
Note Time: Note Text:

0:01:25 Definition: const is used to declare variables that cannot be


reassigned after their initial assignment.

0:02:12 let (Block Scope Variable)


Definition: let is used to declare variables that are limited to the block,
statement, or expression where they are used.
let count = 0;
if (true) {
let count = 1; // This count is different from the outer count
console.log(count); // Outputs: 1
}
console.log(count); // Outputs: 0

0:02:59 var is function-scoped, meaning it is accessible throughout the


function where it is declared.
let and const are block-scoped, meaning they are only accessible within the block
(e.g., {}) where they are declared.

-----------------------------------------------
Video: Make sense of objects
-----------------------------------------------
Note Time: Note Text:

0:01:39 Definition: An object is a collection of related data and


functions (called properties and methods) bundled together.

0:02:12 Creating an Object


Example:
javascript
var course = new Object();
course.title = "JavaScript Essential Training";
course.instructor = "Morten Rand-Hendriksen";
course.level = 1; // 1 for beginner
course.published = true;
course.views = 0;

0:02:36 Shorthand Method:


javascript
var course = {
title: "JavaScript Essential Training",
instructor: "Morten Rand-Hendriksen",
level: 1,
published: true,
views: 0
};

-----------------------------------------------
Video: Object constructors
-----------------------------------------------
Note Time: Note Text:

0:00:05 Adding Methods to Objects:


course.updateViews = function() {
return ++course.views;
};
course.updateViews(); // Increases the views by 1

0:00:05 Accessing Object Properties: console.log(course.title); //


Outputs: JavaScript Essential Training

0:01:56 What is an Object Constructor?


Definition: An object constructor is a template for creating multiple objects with
the same structure. javascript
function Course(title, instructor, level, published, views) {
this.title = title;
this.instructor = instructor;
this.level = level;
this.published = published;
this.views = views;
this.updateViews = function() {
return ++this.views;
};
} this Keyword: Refers to the current object being created.

0:02:57 Using the Object Constructor


Creating New Objects:
javascript
var course1 = new Course("JavaScript Essential Training", "Morten Rand-Hendriksen",
1, true, 0);

0:03:47 Accessing Properties and Methods: javascript


console.log(course1.title); // Outputs: JavaScript Essential Training

-----------------------------------------------
Video: Closures
-----------------------------------------------
Note Time: Note Text:

0:00:01 The code below exemplifies a more complex usage of closures.


Remembering that the ** operator performs a 'power of' operation, what will be
returned when you call var1(4) and var2(3)?

function power(base) {
return function(exp) {
return (base**exp);
};
}
var var1=power(2);
var var2=power(3);

var1 = power(2);:
This sets base to 2.
var1 is now a function that takes an exponent and returns 2 ** exp.

var2 = power(3);:
This sets base to 3.
var2 is now a function that takes an exponent and returns 3 ** exp.

Now, when you call these functions:


var1(4):

This evaluates to 2 ** 4, which is 16.

var2(3):
This evaluates to 3 ** 3, which is 27.
Summary of Returns:
var1(4) returns 16.
var2(3) returns 27

0:00:01 What will be printed to the console as the following script is


running?

var sqrt=(function(x) {
console.log(x*x);
})(my_number)

my_number=5;

This code will error out.

Functions are best described as _____ within the JavaScript program. mini-programs

Can also Access properties of an object using square brackets ([]).javascript


var course = { "WP:image": "image.jpg" };
console.log(course["WP:image"]); // Outputs: image.jpg

0:00:44 What is a Closure?


Definition: A closure is a function that retains access to its outer function's
variables even after the outer function has finished executing.
How It Works
Outer Function: Defines variables and an inner function.
Inner Function: Uses variables from the outer function.
Execution: When the outer function completes, the inner function still has access
to the outer function's variables.

0:01:00 Outer Function: doSomeMath


javascript
function doSomeMath() {
var a = 3;
var b = 6;
function multiply() {
return a * b;
}
return multiply;
}

Inner Function: multiply


javascript
var theResult = doSomeMath();
console.log(theResult()); // Outputs: 18

***********************************************
Chapter: 5. JavaScript and the DOM, Part 1: Changing DOM Elements
***********************************************

-----------------------------------------------
Video: DOM: The document object model
-----------------------------------------------
Note Time: Note Text:

0:01:27 Browser Object Model (BOM)

The browser itself is an object, and it contains several other objects like the
browser window, navigation buttons, and the document displayed.

0:02:02 Document Object Model (DOM)

The DOM is a model of the HTML document displayed in the browser.


Example: The document object represents the HTML document, and you can access it
using document or window.document.

0:02:59 In the DOM, every piece of content in the HTML is a node, and
each node is treated like an object.
Example: An HTML element like <a> is a node in the DOM. When you apply a CSS rule
to all <a> tags, it targets each <a> node individually.

0:03:31 The DOM creates a tree structure of nodes, representing the


hierarchical relationships between elements.
Example: In a typical HTML document, the <html> node contains two child nodes:
<head> and <body>. The <body> node might contain further nested nodes like <nav>,
<ul>, <li>, and <a>.

-----------------------------------------------
Video: Target elements in the DOM with querySelector methods
-----------------------------------------------
Note Time: Note Text:

0:00:55 querySelector and querySelectorAll:


querySelector: Finds the first element that matches a CSS selector.

Example: document.querySelector('.masthead') finds the first element with the class


masthead.

querySelectorAll: Finds all elements that match a CSS selector and returns them as
a list.

Example: document.querySelectorAll('a') finds all <a> (anchor) tags in the


document.
-----------------------------------------------
Video: Access and change classes
-----------------------------------------------
Note Time: Note Text:

0:02:23 contains: Checks if an element contains a specified class.

Example: document.querySelector('.masthead').classList.contains('masthead')
Explanation: This checks if the element with the class masthead contains the class
masthead and returns true or false.

0:02:23 toggle: Toggles a class on or off.

Example: document.querySelector('.masthead').classList.toggle('masthead')
Explanation: This removes the class masthead if it exists; otherwise, it adds it.
It returns false if the class was removed and true if it was added.

0:02:23 item: Returns the class name at a specified index.

Example: document.querySelector('.masthead').classList.item(1)
Explanation: This returns the second class name in the list of classes on the
element with the class masthead.

0:02:23 remove: Removes one or more classes from an element.

Example: document.querySelector('.masthead').classList.remove('clear')
Explanation: This removes the class clear from the element with the class masthead.

0:02:23 Key Methods of classList


add: Adds one or more classes to an element.

Example: document.querySelector('.masthead').classList.add('new-class')

0:02:23 classList: This property returns a list of the classes on an


element.

Example: document.querySelector('.masthead').classList returns a list of classes on


the element with the class masthead.

0:02:23 Accessing Individual Classes: You can access individual classes


using an index.

Example: document.querySelector('.masthead').classList[1] returns the second class


in the list

0:02:23 Change ID: You can change the ID of an element.

Example: document.querySelector('#showcase').id = 'slideshow' changes the ID from


showcase to slideshow.

Change Class: Use className to change the class of an element.

Example: document.querySelector('.masthead').className = 'new-class' changes the


class to new-class.

0:02:23 Accessing Properties


innerHTML: This property gets or sets the HTML content inside an element.
Example: document.querySelector('.main-title').innerHTML retrieves the HTML content
inside the element with the class main-title.

outerHTML: This property gets or sets the HTML content including the element
itself.

Example: document.querySelector('.main-title').outerHTML retrieves the entire HTML


element and its content.

-----------------------------------------------
Video: Access and change attributes
-----------------------------------------------
Note Time: Note Text:

0:04:29 removeAttribute: Removes a specified attribute from an element.

Example: element.removeAttribute('target')

0:04:29 setAttribute: Adds a new attribute or changes the value of an


existing attribute.

Example: element.setAttribute('target', '_blank')


Explanation: Sets the target attribute to _blank, which makes the link open in a
new tab.

0:04:29 getAttribute: Retrieves the value of a specified attribute.

Example: element.getAttribute('href')

0:04:29 Key Methods to Work with Attributes


hasAttribute: Checks if an element has a specific attribute.

Example: element.hasAttribute('href')

-----------------------------------------------
Video: Add DOM elements
-----------------------------------------------
Note Time: Note Text:

0:01:18 Steps to Add DOM Elements


Create the Element:
javascript
const newElement = document.createElement('figcaption');

Explanation: This creates a new <figcaption> element but does not yet add it to the
document.

Create a Text Node:


javascript
const textNode = document.createTextNode('Your text here');

Explanation: This creates a text node containing the text you want to add inside
the new element.

Append the Text Node to the Element:


javascript
newElement.appendChild(textNode);

Explanation: This adds the text node to the <figcaption> element.

Append the Element to the DOM:


javascript
const parentElement = document.querySelector('figure');
parentElement.appendChild(newElement);

-----------------------------------------------
Video: Apply inline CSS to an element
-----------------------------------------------
Note Time: Note Text:

0:05:15 Access the Element:


javascript
const element = document.querySelector('cta a');

Explanation: This selects the element you want to style. In this case, it's an
anchor tag inside an element with the class cta.

Apply a Single Style Property:


javascript
element.style.color = 'green';

0:05:46 For CSS properties with hyphens (e.g., background-color), use


camelCase in JavaScript (backgroundColor).

0:06:01 Using setAttribute Method:


javascript
element.setAttribute('style', 'padding: 2em; color: white; background-color:
red;');

Explanation: This method sets the style attribute directly, replacing any existing
inline styles with the new ones.

0:06:01 Apply Multiple Styles at Once:


javascript
element.style.cssText = 'padding: 1em; color: white; background-color: red;';

Explanation: The cssText property allows you to set multiple CSS properties.

***********************************************
Chapter: 6. Project: Create an Analog Clock
***********************************************

-----------------------------------------------
Video: Use CSS to move clock hands
-----------------------------------------------
Note Time: Note Text:

0:02:11 Rotate Clock Hands: Use the transform: rotate(deg) property to


rotate the clock hands.

-----------------------------------------------
Video: Show the current time using fancy math
-----------------------------------------------
Note Time: Note Text:

0:00:02 // Create a new Date object


var date = new Date();

// Get the current hour, minute, and second


var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

// Log the current time


console.log(`Current time: ${hours} hours, ${minutes} minutes, ${seconds}
seconds`);
Explanation:
new Date(): This creates a new date object representing the current date and time
based on the user's local time zone.
getHours(): This method retrieves the current hour (0-23).
getMinutes(): This method retrieves the current minute (0-59).
getSeconds(): This method retrieves the current second (0-59).

0:03:27 // Get current time


const date = new Date();
const hr = date.getHours();
const min = date.getMinutes();
const sec = date.getSeconds();

// Calculate degrees
const secPosition = (sec / 60) * 360;
const minPosition = (min / 60) * 360 + (sec / 60) * 6;
const hrPosition = (hr / 12) * 360 + (min / 60) * 30;

// Apply to clock hands


document.querySelector('.second-hand').style.transform = rotate(${secPosition}deg);
document.querySelector('.minute-hand').style.transform = rotate(${minPosition}deg);
document.querySelector('.hour-hand').style.transform = rotate(${hrPosition}deg);

0:03:27 //not for ipa


Steps to Convert Time to Degrees
Understanding the Clock Face:

Seconds and Minutes: The clock face is divided into 60 segments for both seconds
and minutes.
Hours: The clock face is divided into 12 segments for the hours.

Calculating Degrees for Seconds:

Formula: (seconds / 60) * 360


Explanation: Since there are 60 seconds in a minute, each second represents 6
degrees (360/60). Multiply the current second by 6 to get the position.
Example: If the current second is 31, the calculation is (31 / 60) * 360 = 186
degrees.

Calculating Degrees for Minutes:

Formula: (minutes / 60) * 360 + (seconds / 60) * 6


Explanation: Similar to seconds, each minute represents 6 degrees. Additionally,
the minute hand should move slightly based on the current seconds to avoid a
"jumping" effect.
Example: If the current minute is 54 and the second is 40, the calculation is (54 /
60) * 360 + (40 / 60) * 6 = 324 + 4 = 328 degrees.

Calculating Degrees for Hours:

Formula: (hours / 12) * 360 + (minutes / 60) * 30


Explanation: Each hour represents 30 degrees (360/12). The hour hand should also
move slightly based on the current minutes.
Example: If the current hour is 9 and the minute is 56, the calculation is (9 / 12)
* 360 + (56 / 60) * 30 = 270 + 28 = 298 degrees.

-----------------------------------------------
Video: Solve the pesky "return to zero" problem
-----------------------------------------------
Note Time: Note Text:

0:00:01 // Initial positions of the clock hands


let secPosition = 0;
let minPosition = 0;
let hourPosition = 0;

// Function to update the clock


function runTheClock() {
// Create a new Date object
const date = new Date();

// Get the current hour, minute, and second


const hours = date.getHours() % 12; // Use modulo for 12-hour format
const minutes = date.getMinutes();
const seconds = date.getSeconds();

// Calculate the new positions for the hands


secPosition += 6; // 360 degrees / 60 seconds
minPosition += (6 / 60); // 6 degrees / 60 seconds
hourPosition += (30 / 3600); // 30 degrees / 3600 seconds

// Ensure positions reset correctly (optional)


if (secPosition >= 360) secPosition = 0;
if (minPosition >= 360) minPosition = 0;
if (hourPosition >= 360) hourPosition = 0;

// Log the current time and positions (for debugging)


console.log(`Current time: ${hours}:${minutes}:${seconds}`);
console.log(`Positions - Hour: ${hourPosition}, Minute: ${minPosition}, Second:
${secPosition}`);

// Update the styles of the clock hands (example CSS selector)


document.querySelector('.hour-hand').style.transform = `rotate($
{hourPosition}deg)`;
document.querySelector('.minute-hand').style.transform = `rotate($
{minPosition}deg)`;
document.querySelector('.second-hand').style.transform = `rotate($
{secPosition}deg)`;
}

// Set an interval to run the clock function every second


var interval = setInterval(runTheClock, 1000);
// Call the function immediately to set the initial time
runTheClock();

0:00:01 // Function to update the clock


function runTheClock() {
// Create a new Date object
var date = new Date();

// Get the current hour, minute, and second


var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

// Log the current time


console.log(`Current time: ${hours} hours, ${minutes} minutes, ${seconds}
seconds`);

// Here you would update your clock hands based on hours, minutes, and seconds
// Example (pseudo code):
// document.querySelector('.hour-hand').style.transform = `rotate(${(hours %
12) * 30}deg)`;
// document.querySelector('.minute-hand').style.transform = `rotate(${minutes *
6}deg)`;
// document.querySelector('.second-hand').style.transform = `rotate(${seconds *
6}deg)`;
}

// Set an interval to run the clock function every second


var interval = setInterval(runTheClock, 1000);

// Call the function immediately to set the initial time


runTheClock();

***********************************************
Chapter: 7. JavaScript and the DOM, Part 2: Events
***********************************************

-----------------------------------------------
Video: Trigger functions with event handlers
-----------------------------------------------
Note Time: Note Text:

0:03:37 <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling Example</title>
<style>
.hide { display: none; }
</style>
</head>
<body>

<button class="cta-button">Click Me</button>


<div class="alert hide">This is an alert!</div>
<script>
const CTA = document.querySelector('.cta-button');
const ALERT = document.querySelector('.alert');

// Attach the event handler


CTA.addEventListener('click', reveal);

function reveal(e) {
e.preventDefault(); // Prevent the default action
CTA.classList.toggle('hide'); // Toggle visibility of the button
ALERT.classList.toggle('hide'); // Toggle visibility of the alert
}
</script>

</body>
</html>

0:03:37 To prevent the default action (like a link navigating to a new


page), you use the e.preventDefault() method within the event handler function.
Here’s how you can structure your reveal function:
function reveal(e) {
e.preventDefault(); // Prevent the default action
CTA.classList.toggle('hide'); // Toggle visibility of the CTA element
ALERT.classList.toggle('hide'); // Toggle visibility of the ALERT element
}

0:03:37 To attach an event handler, you typically use the


addEventListener method. This method allows you to specify the event type and the
function to be called when that event occurs. Here's an example for a click event:
const CTA = document.querySelector('.cta-button'); // Assuming there's a button
with this class
CTA.addEventListener('click', reveal);

0:03:37 What is an Event Handler?

An event handler is a way to make something happen when a specific event occurs on
a webpage.

-----------------------------------------------
Video: Add and use event listeners
-----------------------------------------------
Note Time: Note Text:

0:01:10 What is an Event Listener?

An event listener is like a sensor that waits for something to happen.

-----------------------------------------------
Video: Pass arguments via event listeners
-----------------------------------------------
Note Time: Note Text:

0:02:54 <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Listener with Arguments</title>
</head>
<body>

<button class="cta-button">Book Now</button>

<script>
const CTA = document.querySelector('.cta-button');

// Function to handle the button click


function reveal(e, current) {
e.preventDefault(); // Prevent the default action
// Toggle button text
current.innerHTML = (current.innerHTML === 'Book Now') ? 'Oops' : 'Book
Now';
}

// Attach the event listener with an anonymous function


CTA.addEventListener('click', function(e) {
reveal(e, this); // 'this' refers to the clicked button
});
</script>

</body>
</html>

***********************************************
Chapter: 8. Project: Typing Speed Tester
***********************************************

-----------------------------------------------
Video: Rundown of HTML markup
-----------------------------------------------
Note Time: Note Text:

0:00:14 elementID.addEventListener(eventName,function(e)
{eventFunction(e,this);},false); (false-->(Bubbling Phase))
Ans:
the elementID

Capturing Phase(true) : The event starts from the root of the document and travels
down to the target element. This phase is also known as the "trickle-down" phase.

Target Phase: The event reaches the target element.

Bubbling Phase: The event bubbles back up from the target element to the root of
the document. This phase is often used for event delegation.

What is the general format you will use when adding an event listener?

the event name; the function to call when the event fires

A webpage needs to resize its font when a button is clicked. You implement the
resizing action by assigning the button's onclick event handler to a custom
function. This approach, however, causes a page reload with every click. How can
you fix it? Call the preventDefault() method on the event handler inside the
custom function.Prevent Default Behavior: Use event.preventDefault() to stop the
form from reloading the page when submitted.

What is the first step in adding event handling to your JavaScript code?

identifying the DOM node the interactive behavior will be attached to

The _____ event will fire when an element loses focus. blur

-----------------------------------------------
Video: Use event listeners to detect typing
-----------------------------------------------
Note Time: Note Text:

0:03:03 HTML Structure:

A textarea is provided for typing, and a button to reset the input.


The target text is displayed for the user to match.
Event Listeners:

keypress Event: This event is detected to start the timer when the user types their
first character. A flag (timerStarted) ensures the timer starts only once.
keyup Event: This is used to capture the current text entered. It triggers the
spellCheck function to compare the user's input with the target text.
Timer and Spell Check:

startTimer Function: Placeholder for your timer logic, which logs that the timer
has started.
spellCheck Function: Compares the input text to the target text and logs whether
the input is correct or needs more typing.
Reset Functionality:

The resetButton is wired to clear the text area and reset the timer status.

0:03:03 <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typing Detection</title>
<style>
#testArea {
width: 300px;
height: 100px;
}
</style>
</head>
<body>

<div>
<p>Type the following text:</p>
<p id="targetText">Hello World!</p>
<textarea id="testArea" placeholder="Start typing here..."></textarea>
<button id="resetButton">Start Over</button>
</div>
<script>
const testArea = document.getElementById('testArea');
const targetText = document.getElementById('targetText');
const resetButton = document.getElementById('resetButton');

let timerStarted = false;

// Event listener for detecting the first keypress


testArea.addEventListener('keypress', function() {
if (!timerStarted) {
startTimer();
timerStarted = true; // Ensure the timer starts only once
}
});

// Event listener for validating input on keyup


testArea.addEventListener('keyup', function() {
const textEntered = testArea.value;
spellCheck(textEntered);
});

// Start timer function (placeholder implementation)


function startTimer() {
console.log("Timer started!");
// You can implement your timer logic here
}

// Function to check spelling


function spellCheck(textEntered) {
const targetTextContent = targetText.textContent;
if (textEntered === targetTextContent) {
console.log("Correct!");
} else {
console.log("Keep typing...");
}
console.log(`Current input: "${textEntered}"`);
}

// Reset button functionality


resetButton.addEventListener('click', function() {
reset();
});

// Reset function to clear the test area and reset the timer
function reset() {
console.log("Reset button has been pressed!");
testArea.value = ''; // Clear the input area
timerStarted = false; // Reset timer status
// Additional reset logic can go here
}
</script>

</body>
</html>

-----------------------------------------------
Video: Build a count-up timer
-----------------------------------------------
Note Time: Note Text:

0:04:57 <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Count-Up Timer</title>
<style>
#testArea {
width: 300px;
height: 100px;
}
</style>
</head>
<body>

<div>
<p>Type in the box below:</p>
<textarea id="testArea" placeholder="Start typing here..."></textarea>
<p>Timer: <span id="timerDisplay">00:00:00</span></p>
<button id="resetButton">Start Over</button>
</div>

<script>
const testArea = document.getElementById('testArea');
const timerDisplay = document.getElementById('timerDisplay');
const resetButton = document.getElementById('resetButton');

let timerInterval;
let timer = [0, 0, 0]; // [minutes, seconds, hundredths]

// Start typing event listener


testArea.addEventListener('keypress', function() {
if (timerInterval === undefined) {
startTimer();
}
});

// Timer function
function startTimer() {
timerInterval = setInterval(runTimer, 10); // Update every 10 ms
(hundredths of a second)
}

function runTimer() {
timer[2]++; // Increase hundredths
if (timer[2] >= 100) {
timer[2] = 0; // Reset hundredths
timer[1]++; // Increase seconds
}
if (timer[1] >= 60) {
timer[1] = 0; // Reset seconds
timer[0]++; // Increase minutes
}
updateDisplay();
}
function updateDisplay() {
const minutes = String(timer[0]).padStart(2, '0');
const seconds = String(timer[1]).padStart(2, '0');
const hundredths = String(timer[2]).padStart(2, '0');
timerDisplay.innerHTML = `${minutes}:${seconds}:${hundredths}`;
}

// Reset button functionality


resetButton.addEventListener('click', function() {
reset();
});

function reset() {
clearInterval(timerInterval);
timerInterval = undefined;
timer = [0, 0, 0]; // Reset timer to 0
updateDisplay(); // Update display to 00:00:00
testArea.value = ''; // Clear the text area
}
</script>

</body>
</html>

-----------------------------------------------
Video: Add a reset button
-----------------------------------------------
Note Time: Note Text:

0:00:06 HTML Structure


First, set up your HTML with a text area and a display for the timer:

html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typing Speed Test</title>
</head>
<body>
<div id="timer">00:00:00</div>
<textarea id="testArea" placeholder="Start typing..."></textarea>
<button id="resetBtn">Start Over</button>

<script src="script.js"></script>
</body>
</html>
JavaScript Implementation
Now, create a script.js file to handle the timer logic:

javascript
Copy code
let timer = [0, 0, 0, 0]; // [minutes, seconds, hundredths, total hundredths]
let interval;
let timerRunning = false;
const timerDisplay = document.getElementById('timer');
const testArea = document.getElementById('testArea');
const resetBtn = document.getElementById('resetBtn');

testArea.addEventListener('input', startTimer);
resetBtn.addEventListener('click', resetTimer);

function startTimer() {
if (testArea.value.length === 1 && !timerRunning) {
timerRunning = true;
interval = setInterval(runTimer, 10); // Update every 10 milliseconds
}
}

function runTimer() {
timer[3]++; // Increment total hundredths
if (timer[3] >= 100) {
timer[3] = 0;
timer[1]++; // Increment seconds
}
if (timer[1] >= 60) {
timer[1] = 0;
timer[0]++; // Increment minutes
}

// Display the time


const currentTime = `${leadingZero(timer[0])}:${leadingZero(timer[1])}:$
{leadingZero(Math.floor(timer[3] / 10))}`;
timerDisplay.innerHTML = currentTime;
}

function leadingZero(time) {
return time <= 9 ? '0' + time : time;
}

function resetTimer() {
clearInterval(interval);
timer = [0, 0, 0, 0]; // Reset timer
timerRunning = false;
timerDisplay.innerHTML = '00:00:00';
testArea.value = ''; // Clear the text area
}
Explanation of the Code
HTML Structure: A basic layout includes a timer display, a text area for typing,
and a reset button.

JavaScript Logic:

Variables: An array timer tracks minutes, seconds, hundredths, and total


hundredths. The interval variable stores the interval ID, and timerRunning keeps
track of the timer state.
Event Listeners: When the user starts typing, the startTimer function initiates the
timer. The reset button clears the timer and text area.
Timer Logic: In runTimer, the total hundredths are incremented every 10
milliseconds. If it reaches 100, seconds are incremented, and similarly for
minutes. The timer is formatted with leading zeros using the leadingZero helper
function.
Reset Functionality: The resetTimer function stops the timer, resets all values,
and clears the text area.
***********************************************
Chapter: 9. Loops
***********************************************

-----------------------------------------------
Video: Loops
-----------------------------------------------
Note Time: Note Text:

0:02:22 For Loop:

Structure: for (initialization; condition; increment) { // code block to be


executed }

Example:
javascript
for (let i = 0; i < 10; i++) {
console.log(i);
}
While Loop:

Structure: while (condition) { // code block to be executed }


Do While Loop:

Structure: do { // code block to be executed } while (condition);

-----------------------------------------------
Video: Looping through arrays
-----------------------------------------------
Note Time: Note Text:

0:00:01 // Select all anchor tags with href attributes starting with
http or https
const extLinks = document.querySelectorAll('a[href^="http"]');

// Loop through the NodeList


extLinks.forEach(link => {
// Check if the link does not already have a target attribute
if (!link.hasAttribute('target')) {
// Set the target attribute to _blank
link.setAttribute('target', '_blank');
}
});

// Optional: Log the updated links to confirm


extLinks.forEach(link => {
console.log(link.outerHTML);
});

***********************************************
Chapter: 10. Project: Automated Responsive Images Markup
***********************************************
-----------------------------------------------
Video: Update img markup with srcset and sizes attributes
-----------------------------------------------
Note Time: Note Text:

0:02:18 // Step 1: Collect all images on the page


const images = document.querySelectorAll('img');

for (let i = 0; i < images.length; i++) {


// Step 2: Get the image source and strip the suffix
let imgSrc = images[i].getAttribute('src');
imgSrc = imgSrc.slice(0, -8); // Remove the last 8 characters (-800.jpg)

// Step 3: Get the data type


let type = images[i].getAttribute('data-type');

// Step 4: Create srcset


function makeSrcset(source) {
const markup = [];
let width = 400; // Start with the smallest size

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


markup.push(`${source}-${width}.jpg ${width}w`);
width += 400; // Increment width by 400
}

return markup.join(', ');


}

const srcset = makeSrcset(imgSrc);

// Step 5: Create sizes attribute


const sizes = {
showcase: '100vw',
reason: '(max-width: 799px) 100vw, 372px',
feature: '(max-width: 799px) 100vw, 558px',
story: '(max-width: 799px) 100vw, 670px'
};

// Get the appropriate sizes value


const sizesValue = sizes[type];

// Step 6: Update the image markup


images[i].setAttribute('srcset', srcset);
images[i].setAttribute('sizes', sizesValue);
}

// Now each image should have the correct srcset and sizes attributes applied.
Explanation:
Image Collection: All images are selected with querySelectorAll.
Suffix Removal: The last eight characters (-800.jpg) are stripped using slice.
srcset Generation: The makeSrcset function creates a list of URLs for different
widths.
sizes Mapping: An object maps each image type to its respective sizes string.
Attribute Update: The srcset and sizes attributes are applied to each image
element.

***********************************************
Chapter: 11. Troubleshooting, Validating, and Minifying JavaScript
***********************************************

-----------------------------------------------
Video: Send troubleshooting info to the console
-----------------------------------------------
Note Time: Note Text:

0:02:05 console.log: This is like writing a note in your notebook. It


helps you see the values of variables or messages at different points in your code.
It's very common and useful for basic troubleshooting.

console.info: This is similar to console.log, but it adds a little "i" icon to your
message, making it stand out as informational. console.error:
This is used to log errors. It shows a red error message in the console, helping
you quickly spot problems.

-----------------------------------------------
Video: Online script linting
-----------------------------------------------
Note Time: Note Text:

0:02:18 What is Linting?


Linting is the process of running a program that analyzes your code for potential
errors. Think of it as a spell-checker for your code. It helps you catch mistakes
and improve code quality before you deploy it.

0:04:05 JSLint and JSHint are online script linting

-----------------------------------------------
Video: Automate script linting
-----------------------------------------------
Note Time: Note Text:

0:02:31 ESLint vs. JSHint:

ESLint: Recommended for command line integration and on-the-fly linting in editors
like Atom.
JSHint: Suggested for online linting but less integrated with development
environments.

-----------------------------------------------
Video: Online script minification
-----------------------------------------------
Note Time: Note Text:

0:00:00 File Naming: The minified file is typically named with a .min.js
extension (e.g., script.min.js)

0:00:00 What is Minification?

Definition: Minification is the process of removing unnecessary characters (like


white spaces, comments) from your JavaScript code to reduce its size.
-----------------------------------------------
Video: Automate script minification
-----------------------------------------------
Note Time: Note Text:

0:01:26 Popular Tools for Minification:

1)1UglifyJS 2)UglifyJS-ES6

***********************************************
Chapter: 12. Bonus Chapter: Ask the Instructor
***********************************************

-----------------------------------------------
Video: What do I learn first? JavaScript? TypeScript?
-----------------------------------------------
Note Time: Note Text:

0:03:27 Arrow Functions are a simpler way to write functions in


JavaScript.
Traditional Function Expression:

Example:
javascript
var sumTotal = function(price, tax) {
return price * tax / 100 + price;
};
console.log(sumTotal(6, 12)); // Output: 6.72 Arrow Function:

Example:
javascript
var sumTotal = (price, tax) => price * tax / 100 + price;
console.log(sumTotal(6, 12)); // Output: 6.72

0:04:28 element.addEventListener('click', function() {


console.log('Element clicked');
});

Arrow Function:
javascript
element.addEventListener('click', () => {
console.log('Element clicked');
});

-----------------------------------------------
Video: Why use the querySelector() and querySelectorAll() methods?
-----------------------------------------------
Note Time: Note Text:

0:01:42 getElementsByClassName: Selects all elements with a specific


class name.
javascript
var elements = document.getElementsByClassName('myClass');

You might also like