parm530
2/7/2018 - 4:06 PM

Javascript Essentials

Intro to js

JAVASCRIPT

  • Javascript is a scripting language that runs in the browser to change the css and html of the document running in the browser
  • simplest js program in console: alert('Hello World!')
    • In console, to enter multiple lines of javascript: SHIFT + ENTER
  • Alternate to alert is using console.log("Hello World")
  • In your HTML page, you can load javascript in 1 of 2 places:
    • In the <head> element, before page has loaded
    • After the <body> element, after page has loaded
    • Using <script> tags

Script files

  • Javascript script belongs in their own file, not within an html doc
  • To load the file in the html doc, within <script> tags (assuming the script file lives in the same directory as the html doc):
<script src="nameofscript.js">
</script>
  • Render blocking occurs when the page has loaded its html, sees the js code, blocks the execution of the html page to download and execute js and then resumes the execution of the html doc.
    • You can asynchronously load the js file but render blocking will occur only when the js is about to execute (doesn't block html while waiting for the js file to download) <script src="nameofscript.js" async></script>
    • You can defer the loading until after the html doc has loaded its content and then the js files will load and execute (even if the script is loading in the head) <script src="nameofscript.js" defer></script>
    • Bad to load js in the head, elements may not have loaded.

Writing Good JS

  • Js is case sensitive
  • Naming convention: camelCase, classes and objects are upcased
  • End each statement with a semicolon
  • Comments- single line //
  • Comments- multi-line /* */

Variables

Declaration

var a;

Expression

var a = 4;

  • Datatypes include: numeric, string, boolean, null and undefined
  • Use the typeof variable method to find out what the variabe's datatype is

Operations

  • a += 4; => a = a + 4;
  • Unary operations: a++, a--, ++a, --a (last 2 are done before and saved)

Conditionals

  • if/else
if (condition is true) {
  //execute this block of code
} else {
  //execute this code
}

//Test for equality use ==
var a = 5;
var b = "5";
console.log(a == b); //true

//Test for identicle use ===
console.log(a === b); //false

//Not operator !
console.log( a !== b);
console.log( a != b);

//Ternary operator: condition ? true : false
a == b ? console.log("Match") : console.log("No Match");

Arrays

var colors;
colors = ['red', 'blue', 'green'];

//OR

var colors = new Array('red', 'blue', 'green');

//Quickly copy the contents of an array;
var newArray = colors.splice();

Functions

  • Named functions - executed when called by name
  • Anonymous functions - executed when triggered by a specific event
  • Immediatley invoked function expressions - ran the moment the broswer catches them
//Named function
function name() {
  //code block
  return something // to make the function return a value
}

//to call the function
name();

//Anonymous function: function stored in a variable
var anon = function() {
  //code block
}

anon();

//Immediately invoked functions
(function() {
  //code block
}()) // () immediatley invoked


Objects

var parm = new Object();
parm.firstName = 'Parm';
parm.lastName = "Sahadeo";

//Alternative way:
var parm = {
  firstName: "Parm",
  lastName: "Sahadeo",
  eat: function() { //Anonymous function
    //does stuff
  }
};

parm.eat();
parm.firstName;

  • Creating an object constructor
function Course(title, instructor, level, published, views) { //capitalize the first letter to suggest a new object
// the arguments will contain all the needed properties of the object

  this.title = title; //this refers to the current object
  this.instructor = instructor;
  this.level = level;
  this.published = published;
  this.views = views;
  this.updateViews = function() {
    return ++this.views;
  }
}

var object1 = new Course(...);
var object2 = new Course(...);
...

object.title === object["title"]
//Dot notation vs bracket notation
//Dot notation used for simple property name
//Bracket notation used to convert a property name to string to maintain its unique prop name


Closures

  • A function within a function that relies on the variables from the outer function:
function doSomeMath() {
  var a = 4;
  var b = 5;
  
  function multiply() {
    var result = a*b;
    return result;
  }
  
  return multiply;
}
var theResult = doSomeMath(); //returns the multiply function
console.log(theResult()); //returns 20, performs the function multiply

DOM

  • Document Object Model (the document is an object!)
  • Window is an object, ask it for its width: window.innerWidth
  • Open a new tab: window.open()
  • Document is a property of the window object! : window.document
  • However, since Javascript lives within the window, you can just call document
  • Every html element within the document is called a DOM node!
  • DOM methods:
    • document.getElementById('');
    • document.getElementsByClass('');
    • document.getElementsByTagName('html_tag');
    • document.querySelector('selector');: gets the 1st matched element
    • document.querySelectorAll('selector'): gets all the matched elements

Adding DOM Elements

  • Create the element
  • Create the text node that goes inside the element
  • Add the text node to the element
  • Add the elment to the DOM tree
  • You can use .querySelector on elements that have been obtained by the .querySelector method
  • Adding or removing a class from an element: document.querySelector().classList.add(class_name) (or .remove(class_name)
var element = document.querySelector(".featured-image");
var theImage = element.querySelector("img"); //selects the image under element variable

//Getting an attribute from an element, using .getAttribute("atr")
var altText = theImage.getAttribute("alt");

//Creating a DOM element
var captionElement = document.createElement("figcaption"); 
//This element is not placed anywhere in the browser, it just sits in the browsers memory

//Create a text node and populate it with the text from the alt attribute above
var captionText = document.createTextNode(altText);
//A text node just contains the text, no actual container/element being used in the html markup

//Append the newly created elements 
captionElement.appendChild(captionText);
//ficaption has the text, need to append the figcaption to element

element.appendChild(captionElement);

//set the alt attribute of the image blank, using .setAttribute
theImage.setAttribute('alt', '');
  
/* Instead of creating the textNode and appending it as a child to the figcaption element
   you can use simply, append (appends a string to a specified parent node), the code can 
   be cleaned up by removing the createTextNode and editing the 2 appendChild methods using 
   append:
*/

captionElement.append(altText);
element.append(captionElement);


JS and CSS

  • JS applies css styles to element INLINE, by accessing the style attribute!
    • It does not write to the stylesheets or any other css on the page
    • Obtain all the inline styles of an element: document.querySelector(" ").style
    • To apply a style to an element: document.querySelector(" ").style.color = 'blue'
      • Simply, just assign a value to the css style
      • For styles that contain dashes -, convert the word to camel case! Ex. border-radius becomes borderRadius
      • Drawback: You will need multiple statements to change the css
      • Use .style.cssText to insert pure css: Ex. document.querySelector.style.cssText = "color: white; background-color: blue;"
  • Using the style method, will add on to the already existing styles
    • To overwrite the current style: document.querySelector('').setAttribute("style", "color: blue")
      • You are able to continue listing more css styles within this method: .setAttribute("style", "color: blue; padding: 1em; border-radius: 50%;")
  • Other attribute methods include:
    • .hasAttribute("style"): does the element have this style?
    • .getAttribute("style"): get the inline style
    • .setAttribute("style", "color: red"): add css property
    • .removeAttribute("style"): remove inline styles
  • REMEMBER: Inline styles overrides the current CSS stylesheet style, best practice is to create a custom css rule through classes and then add and remove classes being applied to the element!

DOM Events

  • Browser level events:
    • load
    • window
    • resize
  • DOM level events (inside the viewport)
    • click
    • focus
    • submit
    • mouse events (click, mouseover, ...)

Event Handlers

var el = document.querySelector('');

function reveal(e) { //e is the event object
  e.preventDefault();  //When the button is clicked, the link takes it to url `/#`
                       //to stop the page from bouncing back to the top of the page on refresh
                       //use .preventDefault() to stop the browser from going to this address
  el.classList.toggle("hide"); //toggle will remove and add this class each time it is executed
}

el.onclick = reveal;

Handling Multiple Events

  • If you use multiple .onclick calls, they will override one another until the last call is made.
  • To have multiple events occur on a single event, add eventListeners to your element:
var el = document.querySelector();

//el.addEventListener("click", function, false)
el.addEventListener("click", reveal, false);
el.addEventListener("click", function() { console.log("Hi"); }, false);


Passing Arguments via Event Listeners

const CTA = document.query....

function reveal() {
  //code
  
  current.innerHTML = ....
  //need access to currently clicked object
}

CTA.addEventListener("click", reveal, false);
//Q: How would you pass the currently clicked object?
//A: Need to wrap reveal in an anonymous function:

CTA.addEventListener("click", function() { reveal(this); }, false);
//this refers to the clicked object, which can now be passed as an argument to reveal
//Q: Need to pass the event object, e, also to prevent default refresh to `/#`, how?
//A: You can't just pass e in to reveal, since it is within an anonymous function.
//Remember where the event object is available to you...
//On the call to click!
CTA.addEventListener("click", function(e) { reveal(e, this); });

//Now you can rewrite reveal as:
function reveal(e, current) {
  e.preventDefault();
  current.innerHTML ...
}

Wrap your function in an anonymous function in order to be able to pass arguments!