Skip to content

Exercises (Part 1): JavaScript for the Web

Jonathan edited this page May 9, 2023 · 9 revisions

Part I

Exercise 0

Note: JavaScript normally loads and runs when a web page loads. All of our JavaScript code will go in πŸ‘‰ script.js πŸ‘ˆ, a file that has already been setup to load when our project loads. In your code editor, re-open script.js if you closed it. Starting on a new/blank line below the code that's already written:

  1. Use the console object's log() method, console.log("..."), to log the message "Hello world!".
  2. Open the console at the bottom of the preview pane and verify that your message was logged.
  3. Modify your code from step 1 to log a new message of your choosing!
console.log('some message');

Exercise 1

document.querySelector('someSelector');

For this exercise, you will use console.log() and document.querySelector()☝ to select specific DOM elements and read their properties.

  1. Select the main element. What is the value of its childElementCount property?
  2. Select an element with the dark class. What is the value of its id property?
  3. Select a p (paragraph) element that's inside an element with ID relaxing-images. What is the value of its innerText property?

Selector hints:

  • Class selector: .dotclassName
  • Element selector: #hashelementId

Exercise 2

Pre-made CSS classes to use: picked, hidden, fun.

document.querySelector('someSelector').classList;

An element's classList property contains a list of its classes.

  • add('classToAdd')β€” adds classToAdd to the classList. If it is already there, nothing happens
  • remove('classToRemove')β€” removes classToRemove from the classList. If it isn't there, nothing happens.
  • toggle('classToToggle')β€” if classToToggle is in the classList, it is removed; if classToToggle isn't there, it is added.
document.querySelector('someSelector').classList.add('classToAdd');
document.querySelector('someSelector').classList.remove('classToRemove');
document.querySelector('someSelector').classList.toggle('classToToggle');

Exercise 3

Pre-made CSS classes to use: hidden, transparent, fun.

  • Variables are created (declared) using the let keyword, followed by another word which beocmes the variable's name.
  • Variables are start with an undefined value and are assigned values using the assignment operator, =.
  • Using a single statement to both declare a variable and assign it a value is called initializing:
let newVariable = valueOfVariable;

Exercise 4

An array is an ordered collection of data. A NodeList isn't an array, but it behaves similarly enough for our purposes.

  • document.querySelectorAll('someSelector')
  • myArray[index]β€” retrieves an element from myArray in the position specified specified by index inside the square brackets ([])

Exercise 5

Pre-made CSS classes: message, reveal.

for loop syntax to loop through an array or list (e.g., myArray):

for (let index = 0; index < myArray.length; index = index + 1) {
 // code to repeat
}

In this exercise, we will use a for loop to reveal a HIDDEN MESSAGE on this web page! First, comment out any code from previous exercises. Now:

  1. The words of the HIDDEN MESSAGE are spread through the page's section elements, but they all have the message class.
  2. Use let to declare a variable named words.
  3. Assign words the result of a querySelectorAll() that would match all the hidden words.
  4. Using a for loop, add() the reveal class to each element in your words variable.
  5. Read the HIDDEN MESSAGE! : )

Part II

Exercise 6

Pre-made CSS classes: is-collapsible, collapsible.

 for (initialization; condition; afterthought) { ... }

This webpage has a number of section elements that have been marked with the class is-collapsible to signal that they are compatible with this behaviour. In this exercise, we will use a for loop to prepare our webpage for having collapsible section elements.

  1. Open your script.js file and comment out any code from previous exercises. We will be building on our new JavaScript code.
  2. Select all elements with the is-collapsible class, store the result in a variable, and use a for loop to add() the collapsible class to each selected element.

Exercise 7

For section elements that are collapsible, whether or not they are open or closed is based on the presence (or absence) of the open class on the section element's header element. In this exercise, we will use event listeners to create usable buttons for the collapsible section elements. Your task is as follows:

  1. Create a callback function for addEventListener() that will toggle() the open class on the currentTarget of the event it is provided (e.g., event.currentTarget).
  2. Select all header elements that are descendant of elements with the collapsible class and store them in a variable. Hint:_ Descendant selectors follow the pattern .className elementName
  3. Add a 'click' event listener to each of these elements, providing the callback function you created above as the listener function.

Hints:

  • Listeners are added to elements using the addEventListener() method of an element. For a mouse click listener (a click event), this typically looks like:
someElement.addEventListener('click', listenerFunctionName)
  • listenerFunctionNameβ€” the name of the function that gets run when the specified event is detected (called a callback function).
  • Function creation:
function functionName (parameterA, parameterB, ...){
 // function code
}
  • functionβ€” JavaScript's keyword for declaring functions.
  • functionNameβ€” the name of the function that's being created; used to run (call) the function.
  • (parameterA, ....)β€” information that the function needs to run properly.
  • { function code }β€” code to run when the function is called.

Exercise 8

The section that contains the elements needed for next exercise's image slideshow is currently hidden. To prepare your webpage for the next exercise, and as a review of some of the things we've covered, your task is as follows:

  • Select the element with ID 'relaxing-images' and remove() the hidden class from it. This element contains everything needed for the slideshow feature. That's it for this exercise!

Exercise 9

The slide show's initial state should display the element with the first image and hide all other elements. To get the slideshow ready for use, your task is as follows:

  1. Inside this section, the slideshow images are each a list item (li) element, they are all contained in an element with the carousel-list class.
  2. Create a variable named imgs to save this collection.
  3. Then, except for the first, hide each element using the hidden class.

Hint: the selector: '.carousel-list li' matches the appropriate list item elements for the slideshow!

Exercise 10

Building on your code from Exercise 9:

  1. Add a 'click' event listener to .carousel-list that uses a callback function named goToNextSibling.
  2. Create a variable, currentImg, and store the first slideshow list item element in it.
  3. Then, create the function goToNextSibling which:
    • Hides currentImg using the hidden class.
    • remove()s the hidden class from the nextElementSibling of currentImg.
    • Updates (reassigns) currentImg to its nextElementSibling.

If need be, use the code scaffold below to get started:

let imgs = document.querySelectorAll('.carousel-list li');
// ...rest of exercise 6 code here...

let currentImg = imgs[0]
function goToNextSibling(event) { 
  // ...your click listener code goes here...
};
document.querySelector('.carousel-list').addEventListener('click', goToNextSibling);

Clone this wiki locally