Reviewing Javascript Fundamentals

Cover image

Almost every day a new Javascript framework is born and it may be good or not for us developers. If you're a beginner in programming, knowing how to code in plain Javascript is a major skill you need to keep and enhance over time. Believe it or not, all those frameworks will be forgotten over time but not the fundamentals.

So for today's blog, I decided to share the notes I took during the time I'm learning Javascript for both ES5 and ES6. Take this as a reviewer whenever you need a refresher in JS.

Let's review Javascript!

Let's look back at some concepts such as the browser object model (BOM) and document object model (DOM).

What is BOM? The browser object model is a collection of different parts that can access by Javascript. It is used to interrogate browser. One of the major components of the browser object model is the window object. The window object is a universal object inside the browser and it is available within the browser once the user accesses a webpage. It can access different things inside the browser. The following are:

  1. Document object - represents your page also called DOM. It represents the whole webpage.
  2. Screen object - contains information of the client.
  3. Navigator object - holds the information about the browser.
  4. History object - history of the pages visited by the user.
  5. Location object - location of the webpage where the user visited.

Window object

window - represents the whole browser
window.name
window.innerWidth
window.innerHeight
window.outerWidth
window.outerHeight
window.close()
window.open()
window.resizeTo(size, size)
window.moveTo(position,position)
window.document
window.screen
window.navitator
windows.history
window.location

Window Object Timing

Run specific code with specified interval time.

//setTimeOut - executed only once

function sayHelloToWorld() {
  alert("Hello, World!");
}

window.setTimeOut(sayHelloToWorld, 2000); // time in milliseconds

setTimeOut(sayHelloToWorld, 2000); // time in milliseconds

// clearTimeOut - use to prevent execution of setTimeOut

var time1 = setTimeOut(sayHelloToWorld, 2000);
clearTimeOut(time1);

//setInterval - repeat execute function at set interval time

setInterval(sayHelloToWorld, 2000);

//clearInterval

time2 = setInterval(sayHelloToWorld, 2000);
clearInterval(time2);

Screen Object

Holds information about the user's screen like dimension, display settings.

window.screen.width - return width value of screen
window.screen.height - return height value of screen
window.screen.availWidth - return available width of the screen
window.screen.avaiHeight - return available height of the screen

window.screen.colorDepth - return color depth settings of the screen
window.screen.pixelDepth - return pixel depth settings of the screen

example to print the width

document.write("available width " + screen.width);

History Object

Contains history of pages visited by the user

window.history.length - find the number of pages history visited by the user
window.history.back() - load previous url
window.history.forward() - load next url
window.history.go(1) - one page forward
window.history.go(-1) - one page backward

Use for user browser detection, browser name, app name.

window.navigator.cookieEnabled - check if cookies are enabled or not
window.navigator.appName - return app name of the browser
window.navigator.appVersion - return app version of the browser
window.navigator.appCodeName - return the app code name of the browser
window.navigator.platform - return the platform of the browser
window.navigator.language - access the language of the browser
window.navigator.javaEnabled - check if java is enabled or not

Location Object

Contains details of the current page location and URL of the browser

window.location = "facebook.com"; - redirect to facebook.com
window.location.href - get current page url
window.location.hostname - get current page host name
window.location.pathname - get the current path name of the page
window.location.protocol - get the protocol of the page. http or https

// assign method use to load documents
location.assign("facebook.com"); - loads facebook.com

//reload method use to reload page
location.reload();

// replace current page with set url
location.replace("facebook.com");

Document Object Model or DOM

  • When the user opens a page on the browser, the browser reads the HTML texts and parses it. The browser builds up a model of the documents structures and then uses this model to draw the page in the screen. This model is called DOM
  • The DOM is constructed as a tree of HTML objects by the browser.
  • When each time you load a webpage inside a browser, the web browser generates the internal representation of the page in the form of structures which is called DOM.
  • The document itself is a document node. All elements are element nodes.

Document Object

  • represents your webpage.
  • when you load your webpage to browser, it becomes document object.
  • it is a child object of window object that accesses all HTML elements of the page.
  • a window is a global object.
  • write method is one of the common methods in browser
document.write("<h1>Leigh Dinaya</h1>");

Accessing Elements and Attributes

// access an element using getElementById

var hElement = document.getElementById("my-heading");
alert(hElement);

// get DOM object value
alert(hElement.innerHTML);

// get DOM object attribute value
alert(hElement.getAttribute("id"));

// get tag name
alert(hElement.tagName);

//access elements using class attribute
var pElements = document.getElementsByClassName("my-paragraph");

alert(pElements);

alert(pElements[0]);

alert(pElements[0].innerHTML);

//loop all through elements
for(var i = 0; i < pElements.length; i++){
  alert(pElements[i].innerHTML);
}

//access elements using tag name
var ulElements = document.getElementsByTagName("ul");
alert(ulElements);

//return inner content for index 1
alert(ulElements[1].innerHTML);

//get elements by tag inside a list
var liElements = ulElements[1].getElementsByTagName("list");
alert(liElements[0].innerHTML);

// get elements by name attributes
var naElements = document.getElementsByName("user-name");
alert(naElements[0].tagName);

//access element using css query. it returns first element
var pElement = document.querySelector("p");
alert(pElement.innerHTML);

var hElement = document.querySelector(#my-heading);
alert(hElement.innerHTML);

//access all p elements in the document
var pElements = document.querySelectorAll("p");
alert(pElements[1].innerHTML);

// access all div with p elements
var pElements = document.querySelectorAll("div p");
alert(pElements[1].innerHTML);

// return ul element at first array
var ulElements = document.getElementsByTagName("ul")[0];
alert("Node name " + ulElements.nodeName);

//node type is use to distinguish different
kinds of nodes such as element node, text node and comment node
alert("Node type " + ulElements.nodeType);

//get node parent
alert("Node parent" + ulElements.parentNode.nodeName);

//get child node inside unordered list
alert("Child node" + ulElements.childNodes);

//get length of child nodes
alert("Length of child node " + ulElements.childNodes.length);

Note: whitespaces are considered as child nodes.

// to remove whitespaces, use
var ulChildNodes = ulElements.childNodes;
for(i =0; i < ulChildNodes.length; i++){
  if(ulChildNodes[i].nodeType == 1){
    alert(ulChildNodes[i].innerHTML);
  }
}

// get first child of a node
var isFirstChild = ulElements.firstChild.firstChild.nodeValue;
alert(isFirstChild);

// get last child of a node
var isLastChild = ulElements.lastChild.firstChild.nodeValue;
alert(isLastChild);

// get previous sibling
alert(ulElements.previousSibling.innerHTML);

How to dynamically add content to the element

How to dynamically add content to the page after being loaded to the browser. Note: this is not permanent. For example. add new list to unordered list

//get the value of unordered list
var ulElement = document.getElementById("my-list");

//create list item node
var newListElement = document.createElement("li");

//create text node for li
var newListText = document.createTextNode("This is a new list item");

//append text node to new list using appendChild method
newListElement.appendChild(newListText);

// append list item to unordered list
ulEment.appendChild(newListElement);

an alternative way to add new element/node using parent node

// get list item using id
var listElement = document.getElementById("list-item-1");
listElement.parentNode.appendChild(newListElement);

// add new element using insertBefore method
// the first argument is the element to be added and
//the second argument is where the new element will be added

listElement.parentNode.insertBefore(newListElement, listElement);

// replace element using replaceChild method
listElement.parentNode.replaceChild(newListElement, listElement);

//creating elements by attributes

var hElements = document.getElementById("my-heading");
hElement.setAttribute("align", "center);

//get anchor
var aElement = document.getElementByTagName("a")[0];
aElement.setAttribute("id","my-link");

Change the content of the dom element or node

var hElement = document.getElementById("my-heading");

//get node value
alert(hElement.nodeValue); // this will return null

// to acess the text node.
alert(hElement.childNodes[0].nodeValue);

alert(hElement.firstChild.nodeValue);

//set node value
hElement.firstChild.nodeValue = "Heading text just changed.";

// set content using textContent property
hElement.textContent = "Heading text just changed.";

//set content using innerHTML property
hElement.innerHTML = "Heading text just changed.";

// set content using outerHTML
//you can change the existing html tag to new element
hElement.outerHTML = "<h2>Heading text just changed.</h2>";

let say you want to change the src value of img element
// you can change the attribute value using javascript dom elements

var imgElement = document.getElementsByTagName("img")[0];
imgElement.setAttributes("src","img-source-link");

imgElement.src = "img-rource=link";

//get anchor by its tag name
var aElement = document.getElementsByTagName("a")[0];
aElement.href = "https://facebook.com";

Modifying element style

How to modify elements style

for example, you want to change the style of heading h1

// get the heading element
var hElement = document.getElementById("my-heading");
hElement.style.color = "green";
hElement.style.border = "1px solid red";
hElement.style.background = "blue";

// modify using css className
hElement.className = ".className";

// remove css classes
hElement.className = "";

or using setAttribute property
hElement.setAttributes("class", ".className");

Remove elements or attributes in the DOM

// get unordered list
var ulElement = document.getElementById("my-list");
ulElement.removeChild(ulElement.childNodes[0]); //removes the first element

Document Element Animation

Here's an example of how to animate an element in the DOM

(function() {
  var imgElement = document.getElementById("my-img");
  var imgTopPosition = 0;
  var imgLeftPosition = 450;

  setInterval(moveImage, 10); //10 milliseconds

  function moveImage() {
    //move down
    if (imgTopPosition < 270) {
      imgTopPosition++;
      imgElement.style.top = imgTopPosition;
    } else if (imgLeftPosition < 720) {
      imgLeftPosition++;
      imgElement.style.left = imgLeftPosition;
    }
  }
})();

Let's Review Javascript: Javascript Events

Javascript is often called as event-driven language.

What is an event?

  • event is a signal from the browser that something has happened.
  • occurs when some sort of interaction takes place on a web page.

Events example

  • when the user page load
  • when the user clicks a button
  • when the user moves the mouse over a certain elements
  • when the user presses down keys on the keyboard
  • when the user resizes the browser window
  • when the user scroll down the browser

Through the use of javascript, you can detect when something happens in the browser and you can react and respond to those events.

Javascript Events

Event Description
onload Browser finished loading page
onclick User clicks on html element
onmouseover Usermoves the mouse over html element
onmouseout User moves out the mouse from html element
onkeydown User pushes a keyboard key

Adding and Removing Element

There are 3 methods/models to add an event handler to an event

  1. inline
  2. element.event
  3. element.addEventListener
// let say we add event handler to a button
// adding inline event inside an element
<button id="btn" onclick="alert('Button clicked!')">Click me</button>

// via function
<button id="btn" onclick="doSomething()">Click me</button>

function doSomething() {
  alert('Button clicked!');
}

// using element.event
<button id="btn">Click me</button>

// get the element first
var btnElement = document.getElementById("btn");
btnElement.onclick = function() {
  alert('Button clicked!');
}

window.onload = function() {
  alert("This page just finished loading");
}

// change the background color of an element when the mouse is hover

var hElement = document.getElementById("heading");
hElement.onmouseover = function(){
  if(this.className == "h-normal"){
    this.className == "h-changed";
  } else {
    this.className = "h-normal";
  }
}

Using addEventListener

<button id="btn2" onclick="alert('Button clicked!')">Change button font size</button>

btn2Element = document.getElementById("btn2");

function changeFontSize() {
  this.style.fontSize = 1rem;
}

btn2.addEventListener("click", changeFontSize);
btn2.addEventListener("click", function(){
  alert("This will not overwrite previous event handler.");
});

// addEventListener does not overwrite previous event handler unlike using element.event

//remove event handler
btn2Element.removeEvent("click", changeFontSize);

Event Object

//get button by its id
var btnElement = document.getElementById("btn2");

function changeBtnFontSize(event) {
  this.style.fontSize = "40px"; //or
  event.target.style.fontSize = 40px
  alert(event.type);
  alert(event.target);
}

btnElement.addEventListener("click", changeBntFontSize);

Event Object Explanation

Whenever an event occurs, it causes its attached function or event handler function, it also passes a single argument to the function which is a reference to the event object. You can give it any name you want, the common name is event or e. The event object contains several properties that describe the event that occured. If you want to get the type of event, you can use the type property of event object to get the type of an event.

// get element by its id
var aElement = document.getElementById("link");
function clickMe(event) {
  alert("Click me.");
  event.preventDefault();
}

aElement.addEventListener("click", clickMe);

// the preventDefault() method will prevent the action of the link element

Cross Browser Event Handling

var addEvent = function(element, type, function){
  if(typeof(addEventListener) !== 'undefined'){
    element.addEventListener(type, function);
  } else if ( typeOf(attachEvent) !== 'undefined'){
    element.attachEvent("on" + type, function);
  } else {
    //element."on" + type; this will generate error
    el["on" + type] = function;
  }
};

// the first condition works on all browser
// the second condition works on IE 8
// the last one just in case both methods aren't supported

// cross-browser remove event
var removeEvent = function(element, type, function){
  if(typeof(removeEventListener) !== 'undefined'){
    element.removeEventListener(type, function);
  } else if ( typeOf(detachEvent) !== 'undefined'){
    element.detachEvent("on" + type, function);
  } else {
    //element."on" + type; this will generate error
    el["on" + type] = null;
  }
};

//cross-browser get the target

var getTarget = function(event){
  //if the user is using latest browser, then this condition will be met
  if( typeof(event.target) !== 'undefined'){
    return event.target;
  } else {
    return event.srcElement;
  }
};

// cross browser preventDefault method

var preventDefault = function(event){
  if( typeof(event.preventDefault) !== 'undefined'){
    event.preventDefault();
  } else {
    event.returnValue = false; // IE
  }
};

// usage

addEvent(btn2Element, "click", changeBtnFontSize);
getTarget(event).style.fontSize = "40px";
preventDefault(event);

Previous

Let's create UI Components in Svelte

Next

Integrating NetlifyCMS to your Gridsome site