CourseNotes_JavaScript Essential Training 2017
CourseNotes_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:
***********************************************
Chapter: 2. The Basics
***********************************************
-----------------------------------------------
Video: Add inline JavaScript to a HTML document
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: Add JavaScript in an external file
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
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 /* ... */.
***********************************************
Chapter: 3. Working with data
***********************************************
-----------------------------------------------
Video: Variables: The catch-all containers of JavaScript
-----------------------------------------------
Note Time: Note Text:
Correct
These three loading methods have helped JavaScript evolve from having to put the
script at the end of the code.
-----------------------------------------------
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!\"";
-----------------------------------------------
Video: Arithmetic operators and math
-----------------------------------------------
Note Time: Note Text:
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
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:
-----------------------------------------------
Video: Properties and methods in arrays
-----------------------------------------------
Note Time: Note Text:
slice(start, end): Creates a new array by copying a part of the original array.
javascript
var newPens = pens.slice(1, 3); // ["blue", "green"]
-----------------------------------------------
Video: Functions in JavaScript
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: Build a basic function
-----------------------------------------------
Note Time: Note Text:
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:
-----------------------------------------------
Video: Variable scope
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: ES2015: let and const
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: Make sense of objects
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: Object constructors
-----------------------------------------------
Note Time: Note Text:
-----------------------------------------------
Video: Closures
-----------------------------------------------
Note Time: Note Text:
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.
var2(3):
This evaluates to 3 ** 3, which is 27.
Summary of Returns:
var1(4) returns 16.
var2(3) returns 27
var sqrt=(function(x) {
console.log(x*x);
})(my_number)
my_number=5;
Functions are best described as _____ within the JavaScript program. mini-programs
***********************************************
Chapter: 5. JavaScript and the DOM, Part 1: Changing DOM Elements
***********************************************
-----------------------------------------------
Video: DOM: The document object model
-----------------------------------------------
Note Time: Note Text:
The browser itself is an object, and it contains several other objects like the
browser window, navigation buttons, and the document displayed.
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.
-----------------------------------------------
Video: Target elements in the DOM with querySelector methods
-----------------------------------------------
Note Time: Note Text:
querySelectorAll: Finds all elements that match a CSS selector and returns them as
a list.
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.
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.
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.
Example: document.querySelector('.masthead').classList.remove('clear')
Explanation: This removes the class clear from the element with the class masthead.
Example: document.querySelector('.masthead').classList.add('new-class')
outerHTML: This property gets or sets the HTML content including the element
itself.
-----------------------------------------------
Video: Access and change attributes
-----------------------------------------------
Note Time: Note Text:
Example: element.removeAttribute('target')
Example: element.getAttribute('href')
Example: element.hasAttribute('href')
-----------------------------------------------
Video: Add DOM elements
-----------------------------------------------
Note Time: Note Text:
Explanation: This creates a new <figcaption> element but does not yet add it to the
document.
Explanation: This creates a text node containing the text you want to add inside
the new element.
-----------------------------------------------
Video: Apply inline CSS to an element
-----------------------------------------------
Note Time: Note Text:
Explanation: This selects the element you want to style. In this case, it's an
anchor tag inside an element with the class cta.
Explanation: This method sets the style attribute directly, replacing any existing
inline styles with the new ones.
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:
-----------------------------------------------
Video: Show the current time using fancy math
-----------------------------------------------
Note Time: Note Text:
// Calculate degrees
const secPosition = (sec / 60) * 360;
const minPosition = (min / 60) * 360 + (sec / 60) * 6;
const hrPosition = (hr / 12) * 360 + (min / 60) * 30;
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.
-----------------------------------------------
Video: Solve the pesky "return to zero" problem
-----------------------------------------------
Note Time: Note Text:
// 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)`;
}
***********************************************
Chapter: 7. JavaScript and the DOM, Part 2: Events
***********************************************
-----------------------------------------------
Video: Trigger functions with event handlers
-----------------------------------------------
Note Time: Note Text:
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>
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:
-----------------------------------------------
Video: Pass arguments via event listeners
-----------------------------------------------
Note Time: Note Text:
<script>
const CTA = document.querySelector('.cta-button');
</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.
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?
The _____ event will fire when an element loses focus. blur
-----------------------------------------------
Video: Use event listeners to detect typing
-----------------------------------------------
Note Time: Note Text:
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.
<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');
// 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:
<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]
// 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}`;
}
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:
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
}
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:
-----------------------------------------------
Video: Loops
-----------------------------------------------
Note Time: Note Text:
Example:
javascript
for (let i = 0; i < 10; i++) {
console.log(i);
}
While Loop:
-----------------------------------------------
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"]');
***********************************************
Chapter: 10. Project: Automated Responsive Images Markup
***********************************************
-----------------------------------------------
Video: Update img markup with srcset and sizes attributes
-----------------------------------------------
Note Time: Note Text:
// 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:
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:
-----------------------------------------------
Video: Automate script linting
-----------------------------------------------
Note Time: Note Text:
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)
1)1UglifyJS 2)UglifyJS-ES6
***********************************************
Chapter: 12. Bonus Chapter: Ask the Instructor
***********************************************
-----------------------------------------------
Video: What do I learn first? JavaScript? TypeScript?
-----------------------------------------------
Note Time: Note Text:
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
Arrow Function:
javascript
element.addEventListener('click', () => {
console.log('Element clicked');
});
-----------------------------------------------
Video: Why use the querySelector() and querySelectorAll() methods?
-----------------------------------------------
Note Time: Note Text: