Best JavaScript Book For Beginners

If your looking to learn JavaScript your in the right place. This is the best JavaScript book for beginners. It’s freely available online with tons of great coding examples. We’ll cover all the basics of JavaScript so you can get started writing your own interactive projects.

This course is for the beginner to intermediate coder or anyone that just wants a refresher on JavaScript Syntax. After reading this article you’ll want to start creating your own JavaScript projects. This is the best way to learn how to code. Use a search engine to find things you don’t know or when you get stuck. There are a lot of great resources out there. Ill include some in this book.

What is JavaScript? Why should I learn it?

JavaScript is one of the 3 languages all web developers must learn. HTML, CSS and JavaScript form the basis of front-end web development. HTML defines the content, CSS is used to design how that content looks and JavaScript is used to program the behavior of web pages. 

JavaScript enables you to create interactive elements, dynamically updating content, control multimedia, animate elements, and modify the content of a page. It works on all modern browsers both on desktop and mobile.

A strong knowledge of JavaScript will allow you to create web applications and browser games. 

How JavaScript Works?

JavaScript is a Client-side Scripting Language. This means it’s a web programming language that works in the browser. JavaScript works by manipulating elements on the page with DOM (Document Object Model). It allows you to make changes to a web page after it has loaded to my it feel more dynamic. Every html element on the page can be access and changed with JavaScript.

Javascript Overview

JavaScript Fundamentals For Absolute Beginners

How To Follow Along With This Java Script Course Online 

Download a code editor to write JavaScript on your computer.
A code editor makes your code easier to read by highlighting the syntax in different colors. It can also help suggest and auto complete code while your typing to save time. Sometimes finding errors can be tricky. A code editor can help you do that too. 

Or you can use an online JavaScript editor

JavaScript Console

You can also test code by pasting it in the JavaScript Console. Errors & warnings will also appear in the console. If your code isn’t working that’s a great place to go to figure out why.

CHROME

To open the console in Chrome, you right-click on a web page and then click “Inspect,” and them developers window will appear. Click the “Console” tab next to elements tab in that window. A quicker way is to use a keyboard shortcut.
MAC: Cmd + Option + J
WINDOWS: Cmd +Shift +J

JavaScript Basics PDF - Javascript Tutorial PDF

JavaScript Basics PDF

Coming Soon – JavaScript Basics PDF download so you can read it from anywhere. No need for an internet connection. Ill include the entire JavaScript Tutorial as a pdf.

Javascript Course Content Examples

JavaScript Course Content Examples

Coming Soon – Download this package to get access to all the JavaScript course content and coding examples.

How do I add JavaScript to a webpage?

To insert JavaScript into a web page, use the <script> tag.  The older method used the type or language attributes. This is no longer required as JavaScript is now the default scripting language inside the browser.

Option: 1 (Old Way)

<script language="javascript">
// Javascript code here
</script>

Option 2: (New Way / Shorthand)

<script>
// Javascript code here
</script>

Option 3: Load An External JavaScript File

<script type="text/javascript" src="script.js"> </script>
Scripts can be placed in external files. This is considered best practice as it keeps HTML and JS separate. This is known as separation of concerns. You can do this by keeping your code in a .js file.

Option 3: Load An External JavaScript File

<noscript>
Please Enable Javascript to View This Page Properly!
</noscript>

Adding Comments In JavaScript

Use comments to explain what is going on in your code. They are just there to create notes for yourself and others about what the code does. This will help you remember what you did if you come back to the project after some time. If you work on a team it’s important to help others understand your code.

A single line comment start with //. Any text between // and the end of the line will be ignored. A multi line comment starts with a /* and ends with a */

You can also use comments to disable blocks of code. This is good when you are testing to see which part of the code is causing an error. Sometimes you may want to try out another version of code without deleting what you have already done.

// Inline comment or single line comment
var number = 6; // Good way to add a comment to the end of a line of code.
  
/*
Multi
Line 
Comments 
*/
 
/*Commenting out lines of code. 
document.getElementById("myHeader").innerHTML = "My First Headline";
document.getElementById("myParigraph").innerHTML = "My first paragraph.";
*/
 
//document.getElementById("myHeader").innerHTML = "My First Headline";

Storing & Manipulating Data With Variables

Variables are containers for storing data.  A variable name is a label that points to this data that will allow you to access and manipulate this stored data. Creating a variable is called declaring it. You declare a variable in JavaScript by using the var keyword. Generally it’s best practice to declare all variables at the beginning of a script. All variables must be identified with a unique name. To assign a value to the variable, use the = sign. A variable declared without a value will have the value undefined. It’s best practice to end all lines of code in JavaScript with a ; semicolon.  It’s not required but it’s considered best practice.

 

There are 3 ways to declare a variable in JavaScript.

  • Var: Global Scope – Can be accessed from anywhere.
  • Let: Local Scope – Only lets you use the variable within the block you declared it in. (Best practice to avoid naming collisions)
  • Const: A variable that can not be changed.

The general rules for creating names for variables are:

  • Variable names can contain letters, digits, underscores, or a dollar sign.
  • Names must begin with a letter and not a number.
  • Names can also begin with $ (but that’s usually reserved for JQuery)
  • Names are case sensitive so (Price and price are different variables)
  • Reserved keywords cannot be used as variable names.
  • It’s best practice to use Camel Case for variable names. First letter of the first word is small. First letter of all following words should be capitalized.

JavaScript Provides 7 Different Data Types:

You can get the type of a variable using the typeof keyword: typeof variable;

  • undefined: variable that hasn’t been defined.
  • null: Means nothing. Set a variable to be nothing.
  • boolean: Set a variable to true or false.
  • number: Variable that contains any number.
  • string: Variable that contains any text.
  • symbol: A symbol may be used as an identifier for object properties and dynamically produces an anonymous, unique value.
  • object: An object can store key value pairs.

Declaring & Assigning Variables.

// Initializes a variable. The value is set to undefined.
// Global Variable or to enclosing function
var variable; 

// Block Scope Local Variable
let variable2 = "Local Scope";

// A variable that can not be changed
const pie = 3.1415926535897932384626433;

// Declaring many variables in one statement.
var person = "Cindy Smith", carType = "Ford", price = 35000;

// Lets you see the value of the variable in the console. Great to debug your code and make sure things are working.
console.log(variable);
console.log(variable2);
console.log(pie);

// Console log multiple variables in one statement
console.log("PERSON: " + person + " CAR TYPE: " + carType  + " PRICE: " + price);

String Variables In Javascript

// String (Text) ---------------------------------------------------------
var customer = "Cindy Smith";
var message = 'Yes I am!';
  
// Concatenate Strings - Joining Strings Together
var customerMessage = customer + ": " + message;
var fullName = "John" + " " + "Doe";
var ourString = "First sentence. " + "Second sentence."
var myStr = "Hello, my name is " +  fullName + " and i'm a happy coder!";

console.log(customer);
console.log(message);
console.log(customerMessage);
console.log(fullName);
console.log(ourString);
console.log(myStr);
console.log(typeof customer); // Gets type of variable
String Variables in Javascript

Find The Length Of A String

var myFirstName = "Nathan Ergang";
lengthOfFirstName = myFirstName.length;

console.log("My first name is " + myFirstName + ". That has " + lengthOfFirstName + " characters in it.");

// CONSOLE: My first name is Nathan Ergang. That has 13 characters in it.

Advanced Strings

// Add HTML to a variable
// Using a backtick is the easiest way to add "QUOTES" into a sting.
var HTML = `<a href="http://www.GreenMarketing.ca"> Link </a>`;
 
// You could also just use single quotes.
var HTML = '<a href="http://www.GreenMarketing.ca"> Link </a>';
 
// You can also use an escape character () BACK SLASH.
// It makes the code harder to read so I prefer the first 2 options.
var HtmlLink = "<a href="http://www.GreenMarketing.ca"> Link </a>";
 
// When you write inside ${} this is called a template literal.
// It has some special features the result will be computed.
 
var text = `half of 100 is ${100 / 2}`;
console.log(text);    // Console: half of 100 is 50

Escape characters inside a sting.

Some chatacters don't work inside a sting and need to be escaped to work.

Quote  \’
Double Quote \”
Back Slash  \\
New Line  \n
Carriage Return
(Simular to new line)
 \r
Tab \t
Backspace \b
Form Feed
A form feed is a page-breaking. Forces the printer to start a new page.
\f

 

Bracket Notion

Get a character within a specific index of the string. Remember that javaScript uses ZERO BASED INDEXING which starts at 0 not 1.

var myFirstName = "Nathan Ergang";
firstLetterOfTheString = myFirstName[0];
lastLetterOfTheString = myFirstName[myFirstName.length -1];

console.log("The first letter of the sting is " + firstLetterOfTheString + " and the last letter is " + lastLetterOfTheString + ".");
// CONSOLE: The first letter of the sting is N and the last letter is g.
 
/* ERROR: You can not change an individual character's value. This will give an error or won't take any effect */
myFirstName[0] = "E";

Numbers & Variables In Javascript

In JavaScript, just like in algebra, we can use variables in an expression.

Number Variables

// Numbers
var price_1 = 3;
var price_2 = 10.99;
var total = price_1 + price_2;

console.log(price_1 + " PLUS " + price_2 + " = " + total);
console.log(typeof total); // Gets type of variable
Number Variables Javascript

Javascript Expressions

var totalCost = price_1 + price_2;
var sum = 10 + 12 + 33;
var difference = 50 - 10;
var product = 10 * 10;
var quotient = 100 / 10;

// Increment a number
var myIncrement = myIncrement + 1;
myIncrement++;       	// shorthand
 
// Decrements a number
var myDecrement = myDecrement - 1;
myDecrement--;       	// shorthand 

// Find the remainder
var remainder = 44 % 10;	//4
 
// Determine if a number is even or odd by checking the remainder of 2
var remainder = 44 % 2;	

// Variable = Itself + a number
var a = a + 40;
a += 40;  	//Shorthand
 
// Variable = Itself - a number
a = a - 40;
a -= 40;  	//Shorthand
 
// Variable = Itself multiplied by a number
a = a * 40;
a *= 40;  	//Shorthand
 
// Variable = Itself divided by a number
a = a / 40;
a /= 40;  	//Shorthand

Javascript Arrays - Storing Data In Lists

Arrays are a way to store multiple values in one variable. They’re great for storing a list of items. Creating an array is similar to creating a variable except you assign it with square brackets with your list of items inside . Make sure to wrap string items in quotes "string".

Creating Arrays

var array_name = [1, 2, 3]; 
console.log(array_name);

// You can empty an array like this. Removes all existing values. 
array_name = [];
console.log(array_name);    

// Creates an empty array
var empty_array = []; 

// Array of fruits 
var fruits = ["banana", "apple", "orange", "grape"];
console.log(fruits);
  
// Arrays can span multiple lines
var cars = [
  "Ford",
  "Tesla",
  "Volvo"
];
console.log(cars);

/* You can also create an array this way with the new keyword. The method above is preferred as it’s easier to read and faster to execute. This is just to show you another way of doing things that you might see */
var travel = new Array("Vietnam", "Canada", "Thailand", "Japan");
console.log(travel);

Access The Elements Of An Array

You can access the values by referring to an index number in the array. Array indexes start with 0 so the first item will have an index of 0.

Accessing Array Elements

// Create 2 Arrays
var fruits = ["Banana", "Apple", "Orange", "Grape"];
var cars = ["Ford", "Tesla", "Volvo"];

// Stores the first element in the car array "Ford" in a variable.
var name = cars[0]; 
console.log(name); 

// Prints out Banana in the console.
console.log(fruits[0]);  

// Changing a value of an element in an array. 
// You CAN modify an array with bracket notation unlike variables.
fruits[0] = "Water Melon";
console.log(fruits[0]);  

Nested Arrays [Multi Dimensional Arrays]

A nested or multidemensional array is an array inside of an array or an array of arrays.

Nested Arrays

// Nested Array / Multi Dimensional Array - An array inside an array
var multiDimensional = [   
   ["Universe 1", 34823], ["Universe 2", 19282]   
];
console.table(multiDimensional);
 
// Flatten a multidimensional array into one array
console.table(multiDimensional.flat(Infinity));
 
// Select a single value within a multidimensional array
var universeCoordinate = multiDimensional[0][1];  
console.log(universeCoordinate);

Array Methods

toString() Converts an array to a string with each value separated with a comma.
join() Joins an array into a string but allows you to specify your own separator.
pop() Removes the last value from an array. It can also return the last element in the array.
push() Adds a new element to the end of an array. It can also return the length of the new array.
shift() Removes the first element of the array. It can also return the value that was shifted out of the array.
unshift() Adds a new value to the beginning of an array.
splice() Add new elements to an array at a specified point.
concat() Creates a new array by joining 2 arrays together.
slice() Slices out a section of an array into a new array. It does not remove any values from the source array. Can take up to two arguments. A start and an end point.

JavaScript Conditional Logic - If Statements

If statements are used to make decisions in code. If this happens then do this. If not, do this instead. The order matters once the first condition is met it does not check any other conditions.

Use the else if statement to specify a new condition if the first condition is false. Use the else statement to specify a block of code to be executed if all other conditions are false

If Statements Syntax

if (val > 10) {
// Value is greater than 10
}
else if (val < 5) {
// Value is smaller than 5
}
else {
// Value is between 5 and 10
}

Check to see if a variable is an array using .isArray()

var activities = ["Yoga", "Working", "Sports", "Reading"];
var car = "Ford";
if (Array.isArray(activities)) {
    console.log(activities + " Is an array!");
}
if (Array.isArray(car) != true) {
    console.log(car + " Is not an array!");
}

 Comparison Operators

== Equal operator

= assigns
== compares 

=== Strict equal operator  

There is no variable type conversion.
Meaning a string does not equal an integer.
3 === 3   True
3 === ‘3’  False

!= NOT equal !== Strict NOT equal
> Greater than < Less than
>= Greater than or equal to <= Less than or equal to
&& AND operator

If (val <= 50 && val >=25) {
// Both these must be true
}

|| OR operator

If (val < 50 || val >20) {
// if val is 49 - 21
}

JavaScript Switch Statements

The switch statement allows you to perform different actions based on different conditions. It then runs a block of code based off of those conditions.

The default keyword specifies the code that will run if there is no match.

The Break Keyword stops the execution inside the switch block. Used to jump outside of the switch statement and not make any further checks. The last condition doesn’t need a break as that happens automatically.

Switch Statements - Lets you know what day it is.

var day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  default:
    day = "Saturday";
}
console.log("Today is " + day);
document.write("Today is " + day);

Ternary Operator

The Ternary Operator ? Is a shortcut for If/Else Statements. Allows you to shorten the condition into one line. It will assign a value to a variable based on some condition. The downside is it can make the code harder to read.

String Variables In Javascript

(condition) ? 'If true' : 'If False';

String Variables In Javascript

// Ternary Operator: If > .5 multiply by 1 if not -1
// Randomizes direction of velocity
vel = 100 * (Math.random() > .5 ? 1: -1);

JavaScript Functions

A function is a block of code that is designed to perform a task that can be used over and over again. Functions are very important in Javascript.

JavaScript Built In Functions

console.log(); // Writes out text to JavaScript Console 

Create Your Own Functions

The Function Keyword: is used to define a function. It’s followed by its name and parentheses (). Function naming follows the same rules as variables. The code that gets executed when the function is called goes between the curly brackets {}.

Parameters: Are variables listed inside the parentheses as a part of the function definition. Parameters allow you to input data into the function to produce different results.

Creating JavaScript Functions

// Defines the function
function myFunction(parameter1, parameter2) {
// code to execute
}
//Calls the function
myFunction(1,7);

The Return Statement

Stops code from executing inside the function. It also returns a value to the function caller. Every function in JavaScript returns undefined unless otherwise specified. This function doubles its input then returns the value to the caller so that can be read inside the console.

String Variables In Javascript

//Function that doubles the input
function double(input) {
return input * 2;
}
console.log(double(2));  // console will read out number 4

JavaScript Arrow Functions

Arrow functions were introduced in ES6 as a new way for writing function expressions. With them you can accomplish the same result with fewer lines of code. Instead of the function keyword, it uses an arrow => made from an equal sign and a greater than symbol. You don’t need the return keyword or the {} if the function is a single line. Using arrow functions saves typing but in my opinion makes the code more difficult to read.

Arrow Function With No Parameters

const horn = () => {  console.log("Toot")  };
horn();

JavaScript Loops

Loops are used to repeatedly run a block of code over and over again until a condition has been reached. This is often the case when working with arrays. You would want to loop through all the data and perform some kind of action on them. JavaScript offers several ways to run loops.

In terms of best practices and conventions, for loops are for a known number of iterations and while loops are to be executed until their intended job is done.

For Loops

A for loop is made 3 important parts.

Initialization: The starting point of the counter.
Test Statement: Set the end point of the counter. Test to see if the counter has been reached. If it has exited the loop. If not run the code inside the loop until it does.
Iteration Statement: Amount to increase or decrease your counter by.

For Loop Syntax

for ([initialization]; [test condition]; [iteration statement]) {
   // Statement(s) to be executed if test condition is true
}

For Loop - Examples

Count To 10

document.write("Count to 10.." + "<br />");       
for(var count = 1; count <= 10; count++) {
document.write(count + " ");
}   

Lets modify this a little to be a count down timer for a rocket ship.

Countdown Timer

document.write("Starting Countdown.." + "<br />");       
for(var count = 10; count >= 1; count--) {
document.write(count + " ");
}         
document.write("Blast Off!!!!!");

The most common use of a 'for loop' is to loop through an array.

Loop Through An Array

var fruitArray = ["Banana", "Apple", "Grape", "Orange", "Cherry"];

for (let i=0; i< fruitArray.length; i++) {
document.write(fruitArray[i] + "<br/>"); 
}

JavaScript While Loop

This one loops through a block of code as long as a specified condition is true.

While Loop Syntax Example

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

While Loop Example

var c=0;
while (c < 25) {
    console.log(c);
    document.write(c+"<br>")
    c++;
}
Be Careful of the infinite loop.
An infinite loop will keep running forever. If you accidentally make one you can crash your browser or computer. In the above code if you forget to increase the variable used in the condition, the loop will never end. A loop can be terminated with the break keyword.

Break Out of a Loop Example

// Set a condition to true
const iceCapsAreMelting = true;
let polarBearsLeft = 5;
 
// Initiate infinite loop
while (iceCapsAreMelting) {
  console.log(`There are ${polarBearsLeft} polar bears.`);
  document.write(`There are ${polarBearsLeft} polar bears.<br>`);
  polarBearsLeft--;
  // Terminate infinite loop when following condition is true
  if (polarBearsLeft === 0) {
    console.log("There are no polar bears left.");
    document.write("There are no polar bears left.");
    break;
  }
}

Do…While Loop

Similar to the while loop except the block of code will run first, then the condition will be tested to see if it should run again.

Do While Loop Syntax Example

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

DOM – Document Object Model

What is DOM?
DOM or Document Object Model is an interface that allows programs and scripts to dynamically access and update the content of a website. It turns every element on the page into an object and allows you to access it with JavaScript or other languages. This is how you can change, add or delete HTML elements even after the page has loaded.

With DOM you can:

  • Change the content of an HTML element.
  • Change the styles or CSS of an HTML element.
  • Add, delete, hide or perform actions on HTML elements.
  • Change the value of properties.

DOM METHODS
The document object contains all objects on your page. Methods are actions you can do. on those objects.  If you want to access an HTML element on the page you always start with the document object then a method.

document.getElementById() Most common way to access an HTML element is with its ID.
document.getElementsByTagName() Access an element by tag name.
document.getElementsByClassName() Access an element by class name.
document.querySelectorAll(“p.intro”); Finds all HTML elements that match a specified CSS selector
document.createElement(element) Creates a new HTML Element.
document.removeChild(element) Remove an existing HTML element.
document.appendChild(element) Adds an HTML element
document.replaceChild(new, old) Replaces an HTML Element


DOM PROPERTIES
A property is a value you can set or get.

.innerHTML Allows you to get or change the content of an HTML element.
.attribute Allows you to change an attribute of a HTML element.
.style.property Allows you to change the style of an HTML element.
.setAttribute(attribute, value) Allows you to change an attribute value of an HTML element.

How To Change The Content Between HTML Tags With The DOM

Grabs the element by it’s ID & adds HTML content inside that element.

document.getElementById(“text_01”).innerHTML = “<b>New Text!</b>”;

Grabs the element by it’s ID & adds TEXT content inside that element. NO HTML.

document.getElementById(“text_01”).textContent = “New Text!”;

You can also store the element in a variable and perform actions on the variable.

var text = document.getElementById(“text_01”);
text.textContent = “New Text!”;

Change The CSS Styles Of An Element

To change the style of an HTML element use .style followed by the .propertyName. The attribute names are similar to CSS just without the dash. Use camel case instead.

Changes the text color to blue. 

document.getElementById(“text_01”).style.color = “blue”;

Adds a 3px black border to the bottom of the element. 

document.getElementById(“main-header”).style.borderBottom = ‘solid 3px #000’;

Change An Attribute Of An Element.

Changes the image. 

document.getElementById(“myImage”).src = “sad.jpg”;

Change Elements by Class Name.

var items = document.getElementsByClassName(‘list-group-item’);

// Outputs the whole collection of items with this class name to the console.
console.log(items);
//Outputs the second list item to CONSOLE. Starts counting for 0. 
console.log(items[1]);

// Change text of the second list item,
items[1].textContent = “Changed Text In List”;

// To change something about all items with that class name you need to use a loop.
for (var i = 0; i < items.length; i++) {
items[i].style.backgroundColor = “#f4f4f4”;
}

Change Elements By Tag Name.

// Finds all <p>  tags and stores them in a variable 
var pTags = document.getElementsByTagName(“p”);

// Change the background of all <li> elements
var li = document.getElementsByTagName(“li”);

for (var i = 0; i < li.length; i++) {

     li[i].style.backgroundColor = “#f4f4f4”;

}

Change Elements With Query Selector.

Only grabs the first element in the list. You can use any CSS selector.

// Find all <p> tags with class name intro. Classes use a period as a selector.
var pTagsIntro = document.querySelectorAll(“p.intro”);

//# Grabs the elements ID. 
var header = document.querySelector(‘#main-header’);
header.style.borderBottom = ‘solid 4px #ccc’;

// Changes the value of the first input field.
var imput = document.querySelector(‘input’);
input.value = “Hello World”;

// Changes the value of the first submit button.
var submit = document.querySelector(‘input[type=”submit”]’);
input.value = “SEND”;

// Changes the text color of the last list item
var lastItem = document.querySelector(‘.list-group-item:last-child’);
lastItem.style.color = “blue”;

// Changes the text color of the 2nd list item
var secondItem = document.querySelector(‘.list-group-item:nth-child(2)’);
secondItem.style.color = “blue”;

Change Elements With Query Selector All.

Grabs all the elements and stores them in a list. .

// Selects the second <h2> tag and replaces the text
var titles = document.querySelectorAll(‘h2’);
titles[1].textContent = “hello”;

 // Change the background color of all odd & even list items

var odd = document.querySelectorAll(“li:nth-child(odd)”);

var even = document.querySelectorAll(“li:nth-child(even)”);

for(var i =0; i < odd.length; i++){

     odd.style.backgroundColor = “#f4f4f4”; even.style.backgroundColor = “#ffffff”;

}

TRAVERSING THE DOM

Moving up and down with your DOM selection. Looking at parent, sibling & child nodes etc.

THE PARENT NODE:  <h1><b>Text</b></h1>
Element outside an HTML tag. The Parent of <b> is <h1>

var itemlist = document.querySelector(‘items’);
//Send parent node to console
console.log(itemlist.parentNode;)

//Change the style of a parent node
itemlist.parentNode.style.backgroundColor = ‘#f4f4f4’;
//Move up several parents
console.log(itemlist.parentNode.parentNode.parentNode;)
//PARENT ELEMENT – Pretty much Does the same thing
var itemlist = document.querySelector(‘items’);
console.log(itemlist.parentElement);
itemlist.parentElement.style.backgroundColor = ‘#f4f4f4’;
//Move up several parents
console.log(itemlist.parentElement.parentElement.parentElement;)

CHILD NOTE:  <h1><b>Text</b></h1>
The elements inside. <b> is a child of <h1>

// Gets the first child
console.log(itemlist.firstElementChild);
itemList.firstElementChild.textContent = ‘Hello 1’;

// Gets the last child
console.log(itemlist.lastElementChild);
itemList.lastElementChild.textContent = ‘Hello 5’;

SIBLING NODE: <ul><li>Item 1</li><li>Item 2</li></ul>
Elements beside each other. Item 1 & 2 are sibblings of each other.

//NEXT SIBLING
console.log(itemList.nextElementSibling);
//PREV SIBBLING
console.log(itemList.previousElementSibling);
itemList.previousElementSibling.style.color = ‘green’;

CREATE , INSERT DOM ELEMENTS

// Create a div
var newDiv = document.createElement(‘div’);
// Add a class name
newDiv.className = ‘newDivClass’;
// Add an ID
newDiv.id = ‘div1’;
// Add an attribute
newDiv.setAttribute(‘title’, ‘newDivClass’);
// Create a text node
var newDivText = document.createTextNode(‘Hello Word!’);
// Adds the text to the div
newDiv.appendChild(newDivText);
//Add inside the document inside before the <Header> element with container class
var container = document.querySelector(‘header .container’);
var h1 = document.querySelector(‘header h1’);
console.log(“newDiv”);
newDiv.style.fontSize = ’30px’;
container.insertBefore(newDiv,h1);

DELETE DOM ELEMENTS

 

JavaScript Events

An event is something the browser does or something the user does. JavaScript can react to events and then let you run code after the event has been detected. Since JavaScript code is usually several lines long It’s more common to see events calling functions.

Examples of JavaScript Events:

  • Page finishes loading
  • Input field has changed
  • Something has been clicked
  • A key has been pressed
  • Window gets resized
  • When a form gets submitted
  • Get the full list of events here.

Example 1:
 

Example 2:

ADDING AN EVENT HANDLER TO AN HTML ELEMENT (Old Way)

<!--Syntax Example-->
<element event="JavaScript Code To Execute"></element>
 
<!--On click runs some code-->
<button onclick="this.innerHTML = Date()">The time is?</button>
 
<!--On click runs a function-->
<button onclick="displayDate()">The time is it</button>
<p id="showdate"></p>
<script>
function displayDate() {
  document.getElementById("showdate").innerHTML = Date();
}
</script>
 

JAVASCRIPT EVENT HANDLERS (New Way)

This is the better way of handling events because it keeps HTML clean. The JS Events and HTML are Separated. No need to modify the HTML document to get an event to work.

// Grabs the Html Element by it's ID and stores in a variable.
var button = document.getElementById("button");

// Adds a click event to the button and calls a function
button.addEventListener("click", buttonClick);

// The action that happens when button is clicked
function buttonClick(){
  console.log("Button was clicked");
}
 
var button = document.getElementById("button");
var box = document.getElementById("box");
 
button.addEventListener("click", runEvent);
button.addEventListener("dblclick", runEvent);   // Only fires on double click
button.addEventListener("mousedown", runEvent);  // as soon as you click down. No need to lift up
button.addEventListener("mouseup", runEvent);  // Nothing happens till mouse is released
 
//Only for that element itself not it's children
box.addEventListener("mouseenter", runEvent); // Mouse Enters Box
box.addEventListener("mouseleave", runEvent); // Mouse Leaves Box
 
// Includes children inside the box
box.addEventListener("mouseover", runEvent); // Mouse Enters Box
box.addEventListener("mouseout", runEvent); // Mouse Leaves Box
box.addEventListener("mousemove", runEvent); // Inside the box moving the mouse
 
function runEvent(e){
  // Sends data to console about event type
  consule.log("EVENT TYPE:"+ e.type);
  // Changes the color of the box based on mouse position  
  box.style.backgroundColor = "rgb(" + e.offsetX + "," + e.offsetY + ",40)";  
}
 

JAVASCRIPT EVENT PROPAGATION

This is the blanket term for both event bubbling and capturing. This refers to the order in which event handlers are called.

1. EVENT BUBBLING (Default):

When capture = false
Events ripple up from child element all the way to the top of the document. Starts with the element that triggered the event then moves up the DOM tree to the parents in the hierarchy. If this parameter is omitted the default value is false.

2. EVENT CAPTURE:

When capture = true
With event capture it run the function on the way down. Events go from top of the document (The window object) all the way down to the element that was clicked.

// EVENT BUBBLING
document.addEventListener('click', function (event) {
 
    if (event.target.classList.contains( 'className' ) ) {
            //  Event Action Here
    }
 
}, false);




// EVENT BUBBLING
document.addEventListener('click', listener, false); 
function listener(e) {
// Do Something
}

// EVENT CAPTURING
document.addEventListener('click', listener, true);
 

Debugging

JavaScript Objects – OOP: Object Oriented Programming

Procedural Programming:

Procedural programming, also known as inline programming takes the top-down approach. Its basicly a list of instrctions for the computer to follow. It’s a style of programming that uses variables to store data and functions to modify that data.

Usually simple & straight forward for small scripts but often ends in spaghetti code with large programs. This happens because there is an Inter dependency between functions. This can become problematic and break things in large programs.

OOP: Object Oriented Programming
OOP or Object Oriented Programming was invented to solve this problem. Learning OPP is an essential skill for every developer.

It’s a popular style of programming centered around encapsulating data and behavior into objects rather than variables & functions.

With OPP you combine related functions and variables into a unit called an object. Variables inside an object are referred to as properties. Function inside an object are referred to as methods.

EXAMPLES OF OBJECTS:
OBJECT: Car
PROPERTIES:
Model: “Tesla”,
Color: “Red”,
LicencePlateNo: “FG 4589”,
METHODS:
stop();
start();
move();
changeGear();
OBJECT: Local Storage
POPERTIES:
length: 0,
METHODS:
clear();
getItem();
removeItem();
SetItem();
OBJECT: Person
POPERTIES:
firstName: “Nate”,
lastName: “Ergang”,
age: 30,
METHODS:
wakeUp();
eat();
sleep();

4 PILLARS OF OOP

1 ENCAPSULATION:
Encapsulation is the grouping of related variables and functions together into objects to reduce complexity and increase re usability.
2 ABSTRACTION:
Abstraction hides the details and complexity and only shows the essentials. All the inner working of the object are hidden from the outside. This makes the interface of the object simpler.

Abstraction is a process where you hide the implementation details of the object and provide the functionality. Code from outside the object cant touch private methods and properties. You don’t need to create abstractions for every use. Use your judgment to decide when it’s necessary.

3 INHERITANCE:
Allows you to eliminate redundant code.
Define common methods and properties in a generic object. Then have other objects inherit those properties and methods from the parent object. That way you don’t have to duplicate code.
4 POLYMORPHISM:
Polymorphism: Means many forms.
Allows methods inherited from the parent object to behave differently in the child objects. Without having to use switch case statements. It’s the practice of designing objects to share behaviors but be able to override them as needed with something more specific to that object.

Creating Objects

// Object is created with curly braces
const circle = {};
 
// Doesn't duplicate well. You have to copy the code.
// An object is a collection of key value pairs
const circle = {
    //Properties - Holds values
    radius: 1,
    location: {x:1, y:1},
    //Methods - Define logic & behavior
    draw: function() {       
        console.log("Draw Circle!");
    }
};
circle.draw();  //Call draw method
 

Multiple Instances of Objects

2 Ways to create objects with functions. Use these if you plan to create multiple instances of the same object.

function Circle(radius) {
  this.radius = radius;
  this.draw = function() {console.log("Draw circle!");}
  // Shows what this is in console    This: Circle {}
  console.log("This:", this); 
}

// When we use a new operator to call a function it will create an object.
const anotherCircle = new Circle(1); 
anotherCircle.draw();
 
// Constructor = function used to create an object
// Constructor Functions use this and new keywords
function Circle(radius) {
  this.radius = radius;
  this.draw = function() {console.log("Draw circle!");}
  // Shows what this is in console    This: Circle {}
  console.log("This:", this); 
}

// When we use a new operator to call a function it will create an object.
const anotherCircle = new Circle(1); 
anotherCircle.draw();
 

JavaScript Local Storage

Local storage is the ability to store information locally in the browser.  This allows you to save the visitors data even when the user refreashes or leaves the page.  This is good to move data between pages on your site. Each domain willstore data separtly so you only have access to data from your domain. Depending on the device the local storage can hold anywhere from 2Mb – 100MB+ of data. Javascript objects are  converted to a JSON string before being saved in the browser. You can use javascript to read, write and delete data from local storage. You can look at this information in the developer tools under resources >> local stoarge.

The localStorage object comes with these methods:
localStorage.setItem();
localStorage.getItem();
localStorage.removeItem();

// Set a local storage item
var siteName = 'My Site';
localStorage.setItem('siteName', siteName);
// First perameter is the name we will use to lookup data from local storage.
// Second parameter is the variable we are saving the data from

// Access a local storage item
var siteName_ls = localStorage.getItem('siteName');
console.log(siteName_ls);

//Remove item from local storage
localStorage.removeItem('siteName');
var siteData = {
  siteName: 'My Site',
  siteDescription: 'Best website in the World!!'
}
var localData;

// Objects need to be stored as a sting
// You can convert it to a JSON sting by using the JSON.stringify method
// JSON object are stings of text
localStorage.setItem('siteData', JSON.stringify(siteData));
//When we get a json item out of storage we have to convert it back to an object.
// We do this with JSON.parse method
localData = JSON.parse(  localStorage.getItem('siteData')  );

console.log(localData);   // JavaScript Object to console
console.log(  localStorage.getItem('siteData')  );  //JSON data
 

Taking user input from a form & storing it in Local Storage

Let combine everything we’ve learned so far into a little project that takes user input and stores it into local storage. The user can choose to retrieve that data or delete it. Here’s an example and the code that make it work.

Name:
Message:


</p>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Local Storage Example</title>
</head>
<body>

<form id="ls-form">
Name: <input type="text" id="ls-name"><br>
Message:<br>
<textarea name="message" rows="10" cols="30" id="ls-message"> </textarea><br>
<input type="submit" value="Send Data" id="ls-send">
<input type="submit" value="Retrieve Data" id="ls-retrieve">
<input type="submit" value="Delete Data" id="ls-delete">
</form>
<br>
<span id="ls-data">
<span>

<script>
//Variable declarations using document object model
var lsForm = document.getElementById("ls-form");
var lsName = document.getElementById("ls-name");
var lsMessage = document.getElementById("ls-message");
var lsSend = document.getElementById("ls-send");
var lsRetrieve = document.getElementById("ls-retrieve");
var lsDelete = document.getElementById("ls-delete");
var lsData = document.getElementById("ls-data");

//Event Listeners
lsForm.addEventListener('submit', submitForm);  // Fires once you submit form
lsSend.addEventListener("click", sendData);
lsRetrieve.addEventListener("click", RetrieveData);
lsDelete.addEventListener("click", DeleteData);


//Stops the form from submitting and refeshing the page
function submitForm(e) {
e.preventDefault();  
}

//Send Data To Local Host
function sendData() {
console.log("Sending data to local host....");
//Takes the data from the form and stores it in an object.
x = {"name": lsName.value, "message": lsMessage.value};
// Converts the object into JSON and adds it to the local storage object.
localStorage.setItem('siteData', JSON.stringify(x));
}

function RetrieveData() {
//Checks to see if local storage exists
if (localStorage.getItem('siteData') != null){
	console.log("Retrieveing data from local host....");
	// Converts the data back into an object
	localData = JSON.parse(  localStorage.getItem('siteData')  );
	// Converts the data into a string that will look nice on the page
	// /n is a line break
	text = "Name: " + localData.name + ": \n Message:" + localData.message;
	// innerText changes the value of the span element to include our data
	lsData.innerText = text;
}
else { // if not let the user know
	lsData.innerText = "No data in local storage.";
}
}

function DeleteData() {
console.log("Deleting  data from local host....");
localStorage.removeItem('siteData');
}

</script>

</body>
</html>


</body>
</html>

HTML 5 Canvas

The HTML 5 canvas is an HTML element that allows you to draw graphics on the fly with JavaScript. Use it to create cool visualizations, animations and kick ass visual effects. The canvas object has several methods for drawing paths, boxes, circles, text, and adding images. You can also use it to make Javascript Games. It was ment as a replacement for flash. Works best on modern mobile devices and computers. It has fall back features that allows you to display a static image for older computers that don’t support it.

 

Look Below For Some Cool HTML Canvas Examples

How to use the HTML 5 Canvas

Step1: Add the HTML5 Canvas to the screen.

The Id parameter is used grab it with DOM in JavaScript. You can set the height in HTML or you can do that in JavaScript. The box is transparent by default so if you want to see it you will need to add a little CSS. Here are 3 different ways you could do it. Add this to your HTML File.

<canvas id=”myCanvas”></canvas>

 

<canvas id=”myCanvas” width=”200″ height=”100″></canvas>

<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #000000; background-color:white;”>

Step 2. Grab the canvas with DOM

Create a blank JavaScript file and link it to your HTML document. If you plan to have more than 1 canvas you can use the ID selector.

var canvas = document.getElementById(“myCanvas”);

Other wise you could just grab the HTML element.

var canvas  = document.querySelector(‘canvas’);

Step 3. Set the With & Height of the canvas in JavaScript

Sets the width & height to fit the size of browser

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

You can add an event listener that will change the size of the canvas if someone resizes the browser window.

window.addEventListener(‘resize’, function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
})

Step 4. Create a 2D Drawing Object

Create a drawing object to render the graphic elements on. This is called a 2D drawing context. We will reference this every time we want to add or change something on the canvas .

var ctx = canvas.getContext(“2d”);

Step 5. Draw Elements On The Screen

Draw a rectangle on the canvas

Draws a solid blue rectangle.
FillRect PARAMETERS (x,y,width,height)

ctx.fillStyle = “blue”; // Rectange Fill Color (Before)
ctx.fillRect(100,100,50,50); // Draws a rectangle

Draws a red rectangle outline.

ctx.strokeStyle = “red”; // Rectangle stroke Color (Before)
ctx.lineWidth = 5; // Stroke Width
ctx.strokeRect(200,200,50,50); // Draws a rectangle outline

Draw a circle on the canvas

ctx.arc(x,y,radius,start angle, end angle, counter clock wise: true/false );
Creates a blue circle.

ctx.beginPath(); // Starts a new path
ctx.fillStyle = “blue”; // Stroke Color
ctx.arc(200,200,30, 0, Math.PI*2, false); // Creates a circle
ctx.fill(); // Fills the circle in with the color

Creates a circle with a red outline.

ctx.beginPath(); // Starts a new path
ctx.fillStyle = “blue”; // Stroke Color
ctx.arc(200,200,30, 0, Math.PI*2, false); // Creates a circle
ctx.fill(); // Fills the circle in with the color

Draw a line on the canvas

ctx.beginPath(); // Starts a new path
ctx.moveTo(100, 100); // (x,y) start point of the line
ctx.lineTo(200, 50); // (x,y) next end point
ctx.lineTo(300, 150); // (x,y) next end point
ctx.lineTo(400, 50); // (x,y) next end point
ctx.strokeStyle = “red”; // Line Stroke Color
ctx.lineCap = “round”; // Makes the end of the line round
ctx.lineJoin = “round”; // Makes the joining of 2 lines round
ctx.lineWidth = 5; // Stroke Width
ctx.stroke(); // Adds the stroke to the line

Draw text on a canvas.

ctx.font = “30px Arial”; // Sets font size and type
ctx.fillText(“Hello “, 150, 150); // Creates filled text (text,x,y)
ctx.textAlign = “center”; // Sets text alignment

ctx.font = “30px Comic Sans MS”;
ctx.strokeText(“Word!!”, 280, 150); // Creates outlined text (text,x,y)

 

Draw an image

// Create a function that loads in images
function draw_image(x,y,src)
{
// Create a new image object
image = new Image();
image.src = src;
// Wait until image is loaded to draw it
image.onload = function(){
ctx.drawImage(image, x, y);
}
}
// Call the Image function every time you want to draw one
draw_image(0,0,’image.jpg’);
draw_image(100,100,’image.jpg’);

Step 6. Animate Elements

Create an animation loop

function animate() {
requestAnimationFrame(animate); // Function that creates an animation loop

// Add code that draws and animated objects

}

animate(); // Call animation loop

Create a Controllable Sin Wave With Canvas

Add Dat.Gui Javascript Library To Your HTML Doc

dat.GUI is a lightweight controller library for JavaScript. It creates an interface that allows you to modify varables with sliders. This is helpful to be able to change values and see what it looks like without having to refresh the page.

<script type=”text/javascript” src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.js”></script>

More coming soon!

JavaScript Libraries – What’s next?

React - JavaScript Fundamentals

JQuery

jQuery is a lightweight write less, do more JavaScript library. It makes it easier to write JavaScript with less code. It simplifies some of the more complicated parts of JavaScript. JQuery is tailor-made for selecting HTML elements and performing  some kind of action on them. Another great feature of JQuery is browsner compatibility. They did a great job at addressing most of the cross-browser issues in JavaScript. It will work the same on all major browsers. If your looking the first JavaScript library to learn this would be a good place to start.

anime JavaScript fundamental for absolute beginners

Anime.js

Anime is a really cool JavaScript library that let you animate anything. You can create really amazing animations with just a few lines of code. It works with CSS properties, SVG, DOM attributes and JavaScript Objects.

LEARN MORE:
Documentation

React - JavaScript Fundamentals

React

React is an open source JavaScript library for building user interfaces for single page applications. It allows you to create reusable UI components. It was created by a software engineer at Facebook. React is used to build large web applications that change data without needing to refresh the page. React uses a special syntax called JSX. This allows you to mix HTML with JavaScript. Learn More

React - JavaScript Fundamentals

View.js

View is another framework for creating  web applications and user interfaces with JavaScript. It can be combined with other libraries and is a good alternative to Angular and React.

LEARN MORE:
vuejs.org
Tutorials Point
Vue.js – Full Course for Beginners

 

React - JavaScript Fundamentals

Angular.js

Angular is another Js library used to create single page web applications. This one is maintained by google.

LEARN MORE
w3 Schools

React - JavaScript Fundamentals

Node.js

Node.js is designed to build scalable network applications and allows you to run JavaScript on the server. Kinda like PHP but with JavaScript.

Best JavaScript Book For Beginners

Ember.js

Ember.js is a JavaScript framework for creating ambitious web applications. Write less code with templates that automatically update. Ember.js provides tools that let you focus on your app instead of writing the same code you’ve written a hundred times.

React - JavaScript Fundamentals

BackBone.js

Backbone.js gives structure to web applications using MVC (Model, View, Controller). Model is part of your code that retrieves and populates data. View is the HTML representation the data and controller allows you to save the state of the application in the URL.

Best JavaScript Books & Online Resources

WEBDESIGN RESOURCES

WEBDESIGN RESOURCES

WEB DEsign Tools & ResourcesGoogle's ToolsPageSpeed Insights analyzes the content of a web page, then generates suggestions to make that page faster. Give customers more ways to connect and transact with your business. Google My Business™ lets you update...

Staging The DNS On Windows & Mac

Staging The DNS On Windows & Mac

Staging The DNSHow Can I Test My Website Before Switching DNS? Avoid The Painfully Long Waiting Period After Pointing A Domain Name To A New Host. When you change the DNS settings of a domain name there is a painfull 24 - 48 hour waiting period. If you want to skip...

What Did You Think Of Our JavaScript Fundamentals For Absolute Beginners Course?

Facebook Video