Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created February 11, 2020 00:28
Show Gist options
  • Save rodloboz/ca7eb46ec96ed2237824610495eaf93a to your computer and use it in GitHub Desktop.
Save rodloboz/ca7eb46ec96ed2237824610495eaf93a to your computer and use it in GitHub Desktop.

Lecture Notes:

Your're going to code a solution to the TODO list during livecode so no lecture code today 😢

Here are a few takeways and snipplets from the lecture:

SELECTING HTML ELEMENTS:

document.querySelector(CSS_SELECTOR), where CSS_SELECTOR is any valid css selector that you use in css files. Similar to Ruby's find, it returns an element (returns 1 thing only).

document.querySelector('ul > li') // returns the first li in the ul

document.querySelectorAll(CSS_SELECTOR), similar to Ruby's select, it returns an Array-like object (called a Nodelist).

document.querySelectorAll('ul > li') // returns all the li in the ul

ARROW FUNCTIONS

Syntax: () => {} Arrow functions don't have a name, so we store them in const variables.

const renderTodo = (todo, index) => {
  // Do/return something
};

INSERTING HTML

Syntax: element.insertAdjacentHTML(position, htmlString) This will insert an htmlString in the position relative to the element

const todosList = document.querySelectorAll('ul');
todosList.insertAdjacentHTML('afterbegin', '<li>Hello, I am a TODO</li>');

ITERATING THROUGH NODELISTS

querySelectorAll returns a nodelist, which is an Array-like object that can be iterated over with forEach:

const listItems = document.querySelectorAll('ul > li');
listItems.forEach((listItem) => {
  // Do something with each listItem HTML element
});

EVENT LISTENERS

Syntax: element.addEventListener(eventType, callback) eventType: a string specifying the event, some of the most common are the 'click' event and the form 'submit' event; callback: a function that will only be executed when the event is TRIGGERED/FIRED/EMITTED (they mean the same here);

const form = document.querySelector('form');
form.addEventListener('submit', () => {
  // Do something when the form is submitted
});

NOTE: Because form submits reload or navigate away the current page, it is common to pass the event object to the CALLBACK:

form.addEventListener('submit', (event) => {
  event.preventDefault();
  // This stops the default behaviour of the (form) element,
  // i.e., stops the reloading/navigating away from the current page

  // Then do something
});

When we have several elements that should receive the same event listeners, a typical pattern is to iterate over them and attach the event listener for each one of them:

const listItems = document.querySelectorAll('ul > li');
listItems.forEach((listItem) => {
  listItem.addEventListener('click', () => {
    // Do something when each listItem is clicked!
  })
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment