A bootcamp by Pieter Mathys
Belgium
Facebook: Pieter Mathys
Twitter: @mathysp
Email:
mathysp@gmail.com
pieter.mathys@thomasmore.be
JavaScript is the Programming Language for the Web
JavaScript can update and change both HTML and CSS
JavaScript can calculate, manipulate and validate data
JavaScript is a scripting or programming language that allows you to implement complex things on web pages, displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved.
It is the third layer of the layer cake of standard web technologies, the other two being HTML and CSS.
HTML: markup language that we use to structure and give meaning to our web content
CSS: language of style rules that we use to apply styling to our HTML content
JS: scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.
API's?
An application programming interface (API) is an interface or communication protocol between different parts of a computer program intended to simplify the implementation and maintenance of software.
An API may be for a web-based system, operating system, database system, computer hardware, or software library.
An API specification can take many forms, but often includes specifications for routines, data structures, object classes, variables, or remote calls. POSIX, Windows API and ASPI are examples of different forms of APIs.
API's?
An application programming interface (API) is an interface or communication protocol between different parts of a computer program intended to simplify the implementation and maintenance of software.
An API may be for a web-based system, operating system, database system, computer hardware, or software library.
An API specification can take many forms, but often includes specifications for routines, data structures, object classes, variables, or remote calls. POSIX, Windows API and ASPI are examples of different forms of APIs.
Browser APIs are built into your web browser, and are able to expose data from the surrounding computer environment:
Third party APIs are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:
The best way to learn JavaScript is by practicing, thus online courses provide a great learning environment that requires you to complete activities and projects.
Many websites will have free options for their courses, but for $40 or less (usually) you can upgrade to the professional tier and unlock more content.
Lynda ($30/month)
Front-end Masters ($39/month)
Pluralsight ($29/month)
General Assembly ($ varies by course)
Treehouse ($25/month)
Coursera ($ varies by course)
Egghead.io ($40/month — pro)
CodeAcademy ($ varies by course)
An easy way to stay up-to-date on the latest and greatest features in JavaScript is to sign up for weekly email subscriptions. They show up in your inbox without you having to think about it.
For beginners, I recommend starting with the JavaScript and jQuery book below, although I wouldn’t recommend relying too heavily on jQuery as it’s a bit dated and most employers find this to be a deterrent.
Professional JavaScript for Web Developers ($13 — $27)
JavaScript & jQuery ($22)
Mozilla Developer Network is one of the best resources for looking up the answers to your most burning JavaScript questions. I highly recommend reading through their documentation. CSS Tricks is also an awesome website for staying up-to-date on JavaScript.
Or tutorials like:
jsforcats - beginner tutorial
javascript.info - advanced tutorial
Below are some great tools for quickly testing JavaScript (and related frameworks). They require no overhead to set up and are wonderful tools to use when following along to a course.
I highly recommend learning all the ins-and-outs of JavaScript (vanilla JS) before getting to know a framework or library.
Too often, developers jump in to learning React or Vue and don’t understand what’s going on under-the-hood, so these should be seen more as a second step in your JavaScript journey.
A great, and easy, way to learn JS is to follow awesome influencers, or experts in the field. Below are some of the people I enjoy learning from.
Lastly, I highly recommend attending meetups and conferences as often as you can. Conferences can get expensive, however, so meetups can be a great way to meet other JS lovers in your city.
JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link> elements to apply external stylesheets and <style> elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the <script> element.
<html>
<head>
<link rel="styles.css" />
<script>
// JavaScript goes here
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>
</head>
<body>
<p>Click the button to display an alert box.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html><script src="script.js" defer></script>
This is the preferred way.
Using a separate file for JS has a number of benefits.
function myFunction() {
alert("Hello! I am an alert box!");
}<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
Although, this might have some issues with cross-site scripting
& other related security issues.
It's usually better to download the file and host it yourself.
You are allowed to place the script tag anywhere on the page (not just in the <head>).
This is important for loading order.
A common problem is that all the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.
Look up async & defer if you run into these issues.
<button onclick="createParagraph()">Click me!</button>This thing:
onclick="createParagraph()"
Please don't do this.
It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.
A single line comment is written after a double
forward slash (//), e.g.
A multi-line comment is written between the
strings /* and */, e.g.
// I am a comment/*
I am also
a comment
*/Text
alert("This is alert box!"); // display string message
alert(100); // display number
alert(true); // display booleanText
let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`);Text
let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressedText
// Easy debugging
console.log('Hi this is Pieter')With chrome/firefox/safari/... devtools
Can be declared as
let one = 1; // variable stores numeric value
let two = 'two'; // variable stores string value
let three; // declared a variable without assigning a valueThere are 7 data types:
The data type is assigned automatically based on the value. Use typeof to identify the type.
Note: in a "recent" update of JavaScript (ECMAScript 6) a new name for VAR was introduced: LET.
VAR & LET are synonymous and can be used interchangeably.*
But please pick one and stick to it for now. ;-)
You will see LET used a lot in more modern tutorials.
* Not entirely accurate; there are advantages to using let over var. But let's not open that can of worms for now.
var x = 5;
var y = 6;
var z = x + y;
// Decimals
var x = 3.14; // A number with decimals
var y = 3; // A number without decimals
// All numbers are stored as double precision
// floating point numbers.
// The maximum number of decimals is 17,
// but floating point is not always 100% accurate:
var x = 0.2 + 0.1; // x will be 0.30000000000000004// Strings
var carname = "Volvo XC60"; // Double quotes
var carname = 'Volvo XC60'; // Single quotes
// The length of a string is found
// in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;// Arrays
var cars = ["Saab", "Volvo", "BMW"];
var numbers = [1, 2, 5, 7]// Objects
// This code assigns many values (Fiat, 500, white)
// to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};// Declare function
function myFunction() {
alert("Hello World!");
}// Execute function
myFunction;// With parameters
function myFunction(param1, param2) {
alert("Param 1: " + param1 + "; Param 2: " + param2);
}
myFunction('ABC', 'XYZ');| + | Adds two numeric operands. |
| - | Subtract right operand from left operand |
| * | Multiply two numeric operands. |
| / | Divide left operand by right operand. |
| % | Modulus operator. Returns remainder of two operands. |
| ++ | Increment operator. Increase operand value by one. |
| -- | Decrement operator. Decrease value by one. |
var x = 5, y = 10, z = 15;
x + y; //returns 15
y - x; //returns 5
x * y; //returns 50
y / x; //returns 2
x % 2; //returns 1
x++; //returns 6
x--; //returns 4// You can also use the + operator to join text strings
// together (in programming, this is called concatenation).
var name = 'Bingo';
var hello = ' says hello!';
var greeting = name + hello;
// result 'Bingo says hello!'// There are also some shortcut operators available
name += ' says hello!';
// This is equivalent to
name = name + ' says hello!';// When we are running true/false tests
// we use comparison operators. For example:
// === Strict equality (is it exactly the same?)
5 === 2 + 4 // false
'Chris' === 'Bob' // false
5 === 2 + 3 // true
2 === '2' // false; number versus string
// !== Non-equality (is it not the same?)
5 !== 2 + 4 // true
'Chris' !== 'Bob' // true
5 !== 2 + 3 // false
2 !== '2' // true; number versus string
// < Less than
6 < 10 // true
20 < 10 // false
// > Greater than
6 > 10 // false
20 > 10 // true// Simple IF
if(a < b) {
doSomething;
}
// IF ELSE
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}switch(variable){
case 1:
//code to be executed
break;
case 2:
//code to be executed
break;
case n:
//code to be executed
break;
default:
//default code to be executed
//if none of the above case executed
}// What if we want to execute a function on a button press?
// To do this we need to use an event.
guessSubmit.addEventListener('click', checkGuess);Click is just one of many different events, see https://javascript.info/introduction-browser-events for a more complete list.
for (var i = 1 ; i < 21 ; i++) { console.log(i) }var i =0;
while(i < 5)
{
console.log(i);
i++;
}JavaScript includes while loop to execute code repeatedly till it satisfies a specified condition. Unlike for loop, while loop only requires condition expression.
do{
//code to be executed
}while(condition expression)The do-while loop is similar to while loop the only difference is it evaluates condition expression after the execution of code block.
let sum = (a, b) => a + b;
/* This arrow function is a shorter form of:
let sum = function(a, b) {
return a + b;
};
*/
alert( sum(1, 2) ); // 3// Statements are delimited with a semicolon:
alert('Hello'); alert('World');
// Usually, a line-break is also treated as a delimiter,
// so that would also work:
alert('Hello')
alert('World')
// That’s called “automatic semicolon insertion”.
// Sometimes it doesn’t work, for instance:
alert("There will be an error after this message")
[1, 2].forEach(alert)
// Most codestyle guides agree that we should put
// a semicolon after each statement.
// Semicolons are not required after code blocks {...} // Strict mode
// To fully enable all features of modern JavaScript,
// we should start scripts with "use strict".
'use strict';
// Code below hereThis was a very brief summary of the tutorial Part 1 The JavaScript language found over at https://javascript.info/
Visit the source for (a lot) more information.
Debugging is the process of finding and fixing errors within a script. All modern browsers and most other environments support debugging tools – a special UI in developer tools that makes debugging much easier. It also allows to trace the code step by step to see what exactly is going on.
We’ll be using Chrome here, because it has enough features, most other browsers have a similar process`.
Turn on developer tools with F12 (Mac: Cmd+Opt+I).
On the ELEMENTS tab you can see the DOM.
Here you can manipulate the output to test.
A breakpoint is a point of code where the debugger will automatically pause the JavaScript execution.
While the code is paused, we can examine current variables, execute commands in the console etc. We can always find a list of breakpoints in the right panel.
We can also pause the code by using the debugger command in it
That’s very convenient when we are in a code editor and don’t want to switch to the browser and look up the script in developer tools to set the breakpoint.
function hello(name) {
let phrase = `Hello, ${name}!`;
debugger; // <-- the debugger stops here
say(phrase);
}
Call Stack – shows the nested calls chain.
Scope – current variables.
// Easy debugging
console.log('Hi this is Pieter');
// => 'Hi this is pieter'
var name = 'Pieter'
console.log(name);
// => 'Pieter'
var var1 = 20;
console.log('Var 1 is equal to' + var1)
// => 'Var 1 is equal to 20'You can print out any variables, functions, objects, ... as a console object.
The output can be found in the Console of Browser.
Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor.
Scroll down to part 2
Go through ALL chapters.
Feel free to go through part 3, it contains some useful principles/concepts/...
The backbone of an HTML document is tags.
According to the Document Object Model (DOM),
every HTML tag is an object.
Nested tags are “children” of the enclosing one. The text inside a tag is an object as well.
All these objects are accessible using JavaScript, and we can use them to modify the page.
For example, document.body is the object representing the <body> tag.
Running this code will make the <body> red for 3 seconds:
document.body.style.background = 'red'; // make the background red
setTimeout(() => document.body.style.background = '', 3000); // return backHere we used style.background to change the background color of document.body, but there are many other properties, such as:
<!DOCTYPE HTML>
<html>
<head>
<title>About elk</title>
</head>
<body>
The truth about elk.
</body>
</html>Tags are element nodes (or just elements) and form the tree structure: <html> is at the root, then <head>and <body> are its children, etc.
The text inside elements forms text nodes, labelled as #text. A text node contains only a string. It may not have children and is always a leaf of the tree.
There are some other node types besides elements and text nodes.
For example, comments:
<!DOCTYPE HTML>
<html>
<body>
The truth about elk.
<ol>
<li>An elk is a smart</li>
<!-- comment -->
<li>...and cunning animal!</li>
</ol>
</body>
</html>At the right part of the tools there are the following subtabs:
If an element has the id attribute,
we can get the element using the method
document.getElementById(id),
no matter where it is.
<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
// get the element
let elem = document.getElementById('elem');
// make its background red
elem.style.background = 'red';
</script>elem.querySelectorAll(css)
returns all elements inside elem matching
the given CSS selector.
Here we look for all <li> elements that are last children:
<ul>
<li>The</li>
<li>test</li>
</ul>
<ul>
<li>has</li>
<li>passed</li>
</ul>
<script>
let elements = document.querySelectorAll('ul > li:last-child');
for (let elem of elements) {
alert(elem.innerHTML); // "test", "passed"
}
</script>Any CSS selector can be used.
Can use pseudo-classes as well
:hover :before
querySelectorAll returns an array of objects:
elem.querySelectorAll(css)[0] // Gets the first object
elem.querySelectorAll(css)[4] // Gets the fifth objectThe elem.matches(css) does not look for anything, it merely checks if elem matches the given CSS-selector. It returns true or false.
<a href="http://example.com/file.zip">...</a>
<a href="http://ya.ru">...</a>
<script>
// can be any collection instead of document.body.children
for (let elem of document.body.children) {
if (elem.matches('a[href$="zip"]')) {
alert("The archive reference: " + elem.href );
}
}
</script>{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
Have a read:
AJAX lets you:
Read data from a web server - after the page has loaded
Update a web page without reloading the page
Send data to a web server - in the background
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
Mozilla has a great guide to get you started:
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
Find one that works for you.
Basic structure ribbon
https://codepen.io/mathysp/pen/GRgordM
Flex - hover item