JavaScript Review

  1. JS in HTML. Including JavaScript in HTML with script element, with either src attribute or JS code.
    <script src="scripts/site.js" ></script>
    or
    <script>
    /* JS code here */
    console.log('hello from JS!');
    </script>
  2. Variables. Declare variables with let and sometimes const.
    Though you will see the older var, but avoid that.
    You may also see const which declares a constant (a variable that won't be changed).
    let courseName = 'CSCI E-12',
      courseTerm = 'Fall 2022',
      courseInstructor = 'David' ;
  3. Console is your friend. Your browser developer tools will be critical to use, and especially the "Console". Log to the console in JS with
    console.log('hello there!');
  4. When is the code executed?script in head or right before the body close tag.
    But it is good practice to rely on specific events, especially the DOMContentLoaded event!

    The .addEventListener method takes two arguments. The first is the event name as a string, and the second is the function to execute when that event happens.

    document.addEventListener('DOMContentLoaded', function(){
        /* here's where JS goes for when DOM is loaded */
        console.log('the DOM has been loaded and parsed!');
    });
  5. Events - many are user-driven such as click, focus, blur, submit, mouseover, mouseout, keypress.
    And one important one happens when the browser has processed and loaded the HTML DOM — DOMContentLoaded.
    Even listeners are added through JavaScript!
  6. Functions. Functions can be named, and they can also be anonymous (unnamed) when setting event handlers. Functions can have arguements.

    Named function that accepts an argument:

    function square(x) {
      let numberSquared = x*x;
      return numberSquared;
    }

    Anonymous functions — function() {} — are often used in setting event listeners

    document.addEventListener('DOMContentLoaded', function(){
      /* here's where JS goes for when DOM is loaded */
      console.log('the DOM has been loaded and parsed!');
    });
  7. JavaScript gives us ways to access the DOM as well as manipulate it! Some common ways of accessing the DOM are getElementById, querySelector, querySelectorAll as well as classList, classList.add, classList.remove, classList.toggle.
    We can also construct content with methods like createElement, createTextNode, appendChild, and innerHTML