16. Advanced JavaScript and DOM Manipulation

BootCamp by Dr.Angela

1. Adding Event Listeners

  • ex) document.querySelector("button").addEventListener("click", handleClick);
  • Anonymous function
    • ex)
      document.querySelector("button").addEventListener("click", function () {
      // what to do when clicked
      });
  • Apply to multiple elements (using a loop)
    • ex)
      `var numberOfDrumButtons = document.querySelectorAll(“.drum”).length;

for (var i = 0; i < numberOfDrumButtons; i++) {
document.querySelectorAll(“.drum”)[i].addEventListener(“click”, function () {
alert(“I got clicked!”);
});
}`

2. Higher Order Functions

  • Functions that take other functions as arguments or return functions

3. Playing Sounds on a Website

  • ex)
    var audio = new Audio("audio.mp3");
    audio.play();
  • this(keyword) : Refers to the element that triggered the event
    • ex)
      document.querySelector(".drum").addEventListener("click", function () {
      this.style.color = "white";
      });

4. Switch Statements

  • Used to compare a single value against multiple cases
  • ex)
    `switch (value) {
    case “A”:
    break;

case “B”:
break;

default:
}`

5. JavaScript Objects

  • Objects store related data and behavior together
  • Constructor Function : Starts with a capital letter
    • ex)
      function BellBoy(name, age, hasWorkPermit, languages) {
      this.name = name;
      this.age = age;
      this.hasWorkPermit = hasWorkPermit;
      this.languages = languages;
      }
  • Create object : ex) var bellBoy1 = new BellBoy("Timmy", 19, true, ["French", "English"]);

6. Object Methods & Dot Notation

  • Constructor Function Including Methods : ex)
    function BellBoy(name, age, hasWorkPermit, languages) {
    this.name = name;
    this.age = age;
    this.hasWorkPermit = hasWorkPermit;
    this.languages = languages;
    this.moveSuitcase = function () {
    alert(“May I take your suitcase?”);
    };
    }
  • Call method : ex) bellBoy1.moveSuitcase();
  • Dot notation (.) : Used to access properties and methods of an object
    • ex) object.property or object.method()

7. Keyboard Event Listeners

  • keydown : Fires when a key is pressed (includes all keys)
  • keypress : Fires when a character key is pressed (deprecated in modern JS)
  • Check pressed key : ex)
    document.addEventListener("keydown", function (event) {
    console.log(event.key);
    });

8. Callbacks and Events

  • Higher-order function: takes a function as an argument
  • Callback function: the function passed into another function
  • Tip : $0 (DevTools, Refers to the currently selected element in the Elements panel)

9. Adding Animation

  • Using classList : ex) document.querySelector("name").classList.add("pressed");
  • setTimeout(function, milliseconds) : Used to create temporary visual effects

    • ex)
      setTimeout(function () {
      activeButton.classList.remove("pressed");
      }, 100);