Don't like this style? Click here to change it! blue.css

Class 6: Javascript as the interactive web

Before we start analyzing the technical underpinnings of JavaScript I want to make sure you can do your daily web duties with it. It is the only language that runs in all of our browsers and the web-only features are a little different than the language features as a whole.

Hello JavaScript

For our hello world there are three primary ways of getting output: the console, an alert box, and via the website itself (by manipulating "the DOM"):

  
    console.log("hi there");
    alert("hello");
    document.querySelector("body").innerHTML = "Howdy";
  
JS Bin on jsbin.com

Hello Task 1: Change the hello world messages and confirm you get that.

You can also run/inspect javascript on any page you are viewing. On Chrome open the javascript console and start executing at the command prompt. On Firefox you can go through "tools >> web developer" and chose either a console or "scratch pad" to execute large chunks. The other browsers have their own ways in, some require adjusting your settings into developer mode. Most will let you right-click and inspect element. (You can even do this on a connected device.)

Console Task 2: Head to a website on a browser. Open the console. Erase the contents using innerHTML.

Note that innerHTML should not be used with care for user-created strings, it allows "injection attacks" where a user can cause scripts to execute on your page. This is really a problem when one user's text shows on another user's page (and you have cookies). For now use it and we'll do the more verbose version later.

Basic Programming Stuff

Variables

JS is dynamically typed, so you can reassign any variable to anything.

In JavaScript variables are naturally global (other libraries get access) unless you add a keyword like var (local to this execution content / script) or let (local to this block) (BTW let is an ES2015 feature).

      
        var x = 34;
        console.log(x*12 + 32);
      
    

Javascript also does "hoisting" which means you can refer to variable names defined later but values assigned later are not hoisted.

JS Bin on jsbin.com
String Task 3: When you learn a scripting language it is always great to start with string manipulation. This has MDN's list of string methods. With your team pick one of the following sets to master and then share with your team:

Objects and Arrays

In Javascript everything is an object (more on this later). For now we will use this in the banal sense. Squiggle braces create objects which have comma separated key/value pairs. Keys and values are themselves separated by a colon. Arrays are marked by square brackets, 0-index, and have a length attribute which is not called.

JS Bin on jsbin.com

Family Array Task 4: Create an array of objects that represent your family. Use slice to create a new family from the first 2 people. Use splice to separate them from the family. (You will have to google search.)

Loops and Ifs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration. The basic for loop of Javascript looks just like C/C++ syntax. The same with if statements.

JS Bin on jsbin.com

Project Euler Task 5: Go solve https://projecteuler.net/problem=1 using Javascript.

You can also loop through the keys of an array/object using for varname in obj/array.

JS Bin on jsbin.com

Nested Detection Task 6: Adjust my above example so that when the value in the array is itself an object or array it loops through the keys of that object. (Look up the typeof method.)

Basic Site Interactivity

JavaScript isn't actually the magic part of the web. The DOM is. DOM stands for Document Object Model and it's the paradigm that browsers use to allow scripts (Javascript being the main one) to manipulate your site.

Your connection to the DOM is usually two words: document and window.

Console Task 7: Open up the javascript console. Type document. (hit tab if your browser needs that). Take a look at all of the methods. Pick out two and read up on them. Repeat for window..

Selecting Elements

Here is a summary of how you can get access to any particular element in your document (you can use any particular element or the root document as the object that these methods get called on):

Selection Task 8: Head to google.com and open up the javascript console. Save an array of elements which have the 'p' tag. Use the console to deduce how to get the class attribute from the first p tag. Now write a loop that logs every class value from all of the paragraphs you found there.

Class Selection Task 9: Now use one of the classes you found to get all elements that share that class.

Query Selector Task 10: Now use the CSS selector version of the last task. (i.e. document.querySelector('.class_name_here')) Alter that elements innerHTML to be "Your name here rules".

Style Manipulation

You can access and manipulate CSS properties on HTML elements once you have access to that element. element.style gets you the properties and window.getComputedStyle(element) gets you the final values.

JS Bin on jsbin.com

Alter the styles for the whole page by using document.styleSheets[i].cssRules[j].style.propert_name_here = 'value_here' or specific elements using element.style.property_name_here = 'value_here';.

Pirate Salmon Task 11: Go to a popular website. Use javascript to change every color to salmon!

Aside: By the way, I have leaned on jQuery for a long time and only recently have I been motivated to just go vanilla. http://youmightnotneedjquery.com/ is a nice way to find jQuery-free ways of doing things.