HTML & JavaScript Introduction

HOW DOES THE WEB
WORK?

Request / Response

When you navigate to a web page what happens?

Client: Request

Server: Response

Opening a website requires...

  • The client
  • The server
  • An Internet connection
  • TCP/IP
  • HTTP
  • DNS
  • HTML, CSS, & JavaScript
  • Assets

HTML Structure

Language for page markup

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Title of the document</title>
        <style>
            //CSS Styles...
        </style>
    </head>

    <body>
        <h1>Header</h1>
        <p>First paragraph with <em>emphasized text</em>.</p>
        <p>Second paragraph.</p>
        <script>
            //JavaScript code...
        </script>
    </body>
</html>

HTML Document

DOM

HTML Document vs. DOM

HTML documents are delivered as "documents".  Then web browser turns them into the Document Object Model (DOM) internal representation.

HTML documents contain tags, but do not contain the elements. The elements are only generated after the parsing step, from these tags. 

JavaScript syntax

Variables

Declared by prefixing with var

var a = 1;
var b = 2,
    c = b;

Weakly typed

var a = 2;
a = 3.14;
a = 'This is a string';

Initialized with the value undefined

var a;
console.log(a); //undefined
console.log(a === undefined); //true

Data types

  • Primitive values:
    • Number
    • String
    • Boolean
    • null
    • undefined
  • Object:
    • Function
    • Array
    • Date
    • RegExp

Conditional and Iterative blocks

if( a >= 0){
    a++;
} else if(a < -1){
    a *= 2;
}
switch(a){
    case 1:
        a += 1;
        break;
    case 2: 
        a += 2
        break;
    default:
        a = 0;
}
for( var i = 0; i < 5; i++ ) {
  console.log(i);
}
while(a < 100) {
  a++;
}

do {
  a++;
} while(a < 100);

Conditional:

Iterative :

Objects

var animal = {
  isDog: true,
  name: 'Sparky',
  bark: function(){
    return 'Bark!'
  }
} 
  • a hash of key:value pairs;
  • the key can be a Number or a String;
  • the value can be anything and it can be called a property;
  • if a value is a function, it can be called a method.

Example:

Arrays

  • also objects;
  • have numeric properties that are auto-incremented;
  • have a length property;
  • inherits some methods like:
    • push();
    • splice();
    • sort();
    • join();
    • and more.
var array = [1,2,3];

console.log(array.length); //3

array.push("a value");

console.log(array.length); //4

Example:

Functions

  • also objects;
  • have properties and methods;
  • can be copied, deleted, augmented;
  • special, because can be invoked;
  • all functions return a value (implicitly undefined);
  • can return other functions.
//Function Declaration
function fn(x){
   return x;
}

//Function Expression
var fn = function(){
   return x;
}

Example:

Constructor Functions

  • return this when they are invoked with new;
  • this can be modified before it's returned;
  • can return another object.
var Person = function(name){
   this.name = name;
   this.sayName = function(){
      return 'My name is ' + this.name;
   };
};

//Create new instance
var john = new Person('John');

>> john.sayName(); //John
>> john instanceof Person //true
>> john instanceof Object //true

Example:

Prototype

  • a property of the function object;
  • can be overwritten or augmented.
var Person = function(name){
   this.name = name;
   this.sayName = function(){
      return 'My name is ' + this.name;
   };
};

//Create new instance
var james= new Person('James');

//Augment the prototype object
Person.prototype.changeName = function (newName) {
   this.name = newName;
};

james.changeName('Joe');

>>james.sayName(); //Joe

Example:

__proto__

  • it's not directly exposed in all browsers;
  • it's a reference to constructor prototype property.
var Person = function(name){
   this.name = name;
};

Person.prototype.changeName = function (newName) {
   this.name = newName;
};

Person.prototype.sayName = function(){
   return 'My name is ' + this.name;
};

var james= new Person('James');

>> james.hasOwnProperty('changeName'); //false
>> james.__proto__.hasOwnProperty('changeName'); //true

Example:

Variables Scope

No block scope

if(true){
   var inside = 1;
}

>>inside //1

Every variable is global unless it’s in a function and is declared with var

function fn(){
   var private = true;
   //private it's available here
}

>>private //undefined

IIFE (Immediately Invoked Function Expression)

(function(){
   var a = 1;
   var b = 2;

   alert(a + b);
}());

Closures

  • Closures are functions that refer to independent (free) variables.;
  • In other words, the function defined in the closure 'remembers' the environment in which it was created. 
(function(win){
  var a = 1, 
      b = 2,
      sum = function(){
         //Closure Function
         return a + b; 
      }

  win.sum = sum;
})(window);

>> sum()//3
//bad
for (var i = 0; i < 5; i++) { 
   window.setTimeout(function(){ 
      alert(i); // will alert 5 every time
   }, 200); 
} 

//good
for (var i = 0; i < 5; i++) { 
   (function(index) {
      window.setTimeout(function() {
          alert(index); 
      }, 100);
   })(i);
}

Sum it up

  • Follows the prototype model
    • One object can inherit from another
  • Functional language
    • Can pass functions as arguments
    • A function can return another function (Closure)
  • Dynamic:
    • Types are associated with values - not variables
    • Define new program elements at run time
  • Weakly typed:
    • Leave out arguments to methods
    • Access non-existing object properties
    • Truthy and falsy values
    • Implicit conversions: 99=="99"

DOM Manipulation

DOM & Execution Environment

  • the window object represents the window of your browser that displays the document and its properties include all the global variables;
  • the document object represents the displayed HTML;
  • document object has property arrays for forms, links, images, etc. 
  • elements of a document are objects with data and operations, the data being their properties.
<img src="myImage.jpg" alt="my image">
img = { src: "myImage.jpg", alt: "my image" }

Example:

Javascript & the DOM

Javascript possesses incredibly power, it can manipulate the DOM after a page has already been loaded

  • It can change HTML Elements
  • It can change Attributes
  • It can modify CSS
  • It can add new Elements and Attributes
  • It can delete Elements
  • It can react to Events in a page
document.getElementById("id");

document.getElementsByClassName("class_name");

document.getElementsByName("name");

document.getElementsByTag("tag_name");

So, how does Javascript Manipulate the DOM?

Events & event handling

  • an event is a notification that something specific has occurred in the browser
  • an event handler is a script that is executed in response to the appearance of an event
  • events are also JavaScript objects

Event types:

  • click
  • keydown
  • mousedown
  • mouseout
  • mouseover
  • submit
  • much more
<!-- HTML -->
<button id="myButton">Click me</button>

//Js
var element = document.getElementById('myButton');

function eventHandler(){
    alert('You have clicked the button');
}

element.addEventListener('click', eventHandler);

$("#myButton").on('click', function(){
    alert('You have clicked the button');
});

Demo

HTML & JavaScript Introduction

By Alexe Bogdan

HTML & JavaScript Introduction

HTML Structure, JavaScript Syntax, DOM manipulation

  • 1,204