Javascript - DOM 1

Learning Objectives

By the end of this lesson trainees should be able to:

  • Know forms and input elements

  • Define what the DOM is and what it does

  • Use query selectors to retrieve elements from the DOM

  • Use event listeners to respond to events that happen on the DOM

  • Create DOM elements using JavaScript and add them to the DOM

  • Manipulate DOM elements using JavaScript to change their properties

Teacher instruction

  • Second portfolio project start today! Here is the link. The project is individual handin!

  • Husk at sende nogle visualiseringer hvis i finder nogle nice nogle!

Objects handin review

  • Jeg var ikke helt tydelig nok med den her aflevering.

  • Plagiat

    • Der er mange af afleveringerne der minder rigtig meget om hinanden og det er helt fint at blive inspireret af fremgangsmetoder, MEN

    • Husk at skrive hvor i har kode fra, fx nettet

    • Hvilken gruppe i har arbejdet i.

    • Heller lidt for meget her end for lidt.

    • Når det bliver de obligatoriske afleveringer skal i være mere forsigtige. De er eksamenspligtige og kan ende i en plagiatsag der ikke er sjov for nogle. De kan desuden resultere i at blive smidt ud.

  • Peer review of project

  • Aflever via git. Hvis i har svært ved det så ska jeg nok hjælpe!

  • Gode variabelnavne!

  • I har fuldstændig styr på whatToWear. Det er stort! Skide godt klaret

  • Godt løst med funktionen der kører et forloop!

  • Lav pseudokode for den tredje opgave

Flipped classroom videos

Forms and input elements

Forms are used to send data from the client to a server. Often times you need to write your name, email, telephonenumber etc.

Inputs

Inputs are used to get text from a user. This is how an input is defined 👇 Notice that it is selfclosing! Like the img tag

This is probably the most famous input field ever

Google input field

There are different types of input fields. One for numbers, text, telephone number, date. See them all herearrow-up-right

Checkboxes

Checkboxes are used to get a value that can either be true or false. It is typically used for the remember me functionality

Checkbox

Radio buttons

Radio buttons are used to select between a given set of options.

The label tag shows the text for the radio button. What is important is that the id attribute and the for attribute matched their value. Otherwise the label is not connected to the radio button.

Another important thing is that the groups that are together have the same name attribute

Radio buttons

Select

Select is also used to select between a given set of options. It is typically used to select country. The difference from the radio buttons is that in select the user has the possibility to select multiple options!

It is similar to the ul and li. Inside of the select tag there has to be an option tag for each option the user can select. You can give the option tag a value but you dont have to

![Select list](../assets/select box.png)

Buttons

Buttons are used for some kind of interactivity. Should not be used as links!

There are some more form fields but i have covered the most important ones here.

JS in the Browser

Up until now we've been using console.log (and a bit of document.write) to see the results of our code running, because it allows us to focus on writing code and seeing the results instantly. But JavaScript was not meant to be run in console.log: it was meant to make web pages dynamic.

Lots of websites are powered by JavaScript today, and some (like Facebook) cannot function at all without it: it's become that important to the look and feel of the website.

The DOM

Your webpages are made up of a bunch of HTML elements, nested within each other (parents and children). But JavaScript doesn't know about any of that.

Thankfully, in JavaScript we have access to this "DOM" object (Document Object Model) which is actually a representation of our webpage that JavaScript can work with.

Here are two examples, HTML and then the DOM

This is how we would represent the document hierarchy above as a tree of nodes:

DOM representation

Interacting with the DOM using javascript

There are 4 important things to learn when interacting with the DOM

  1. Accessing DOM elements (how to select a specific tag)

  2. Manipulating DOM elements (how to change the tag we selected)

  3. Creating DOM elements (creating new tags we can insert into the page)

  4. Attaching events (how we can run code when fx a button is clicked)

Access DOM elements

The DOM offers a lot of useful functions we can use to find elements on the page. Here are some we'll be using today:

Both .querySelector and querySelectorAll accept a CSS selector as an input.

  • querySelector selects only the first element it finds

  • querySelectorAll selects all elements and returns a NodeList. NodeList can be turned into an array like this: Array.from(document.querySelectorAll("p"));

Manipulate DOM elements

When a element has been selected it can be changed. Everything about the element can be changed

  • The text inside of the tag

  • The classnames

  • Id's

  • Style

Let's try and change the text inside a p tag using innerText 👇

We can even put html inside of the p tag using innerHTML 👇

We can also change the class name of the p tag using.className

Now the p tag only has two class names red and large

Create DOM elements

Using the document, you can also create new elements. These elements will not appear until you append them as a child of another element though:

document.createElement accepts as an input any element type. So for example document.createElement("article") will create a new article element.

Attach events to DOM elements

Once you retrieve an element using .querySelector, you can attach an event to it. An event is any action that can be performed on that element. For now, we will just use the click event:

You will notice in the example that we passed a second argument to addEventListener. That second argument is the function that we want to invoke when that event has happened.

Concrete examples of using the DOM in javascript

Creating a list of hobbies

Let's create a list of hobbies from javascript into the webpage using the DOM

html

javascript

Creating a select list

Let's instead of adding the hobbies as a list then add them as a select tag so we can select one of the hobbies

html

javascript

Getting the selected hobby is a bit tricky. Read herearrow-up-right to get it working

Exercises

Preparation for exercises

Let's work on the code provided herearrow-up-right

That means you have to clone this repoarrow-up-right onto your computer and then find the A-dom-manipulation folder to open in VS code

  1. Open a new project in webstorm from the folder week-5/inClass/A-dom-manipulation

📝 Exercise 1 - level 1

Write JavaScript below that logs:

  1. All the p tags

  2. The first div tag

  3. The element with id jumbotron-text

  4. All the p tags contained inside the .primary-content tag

📝 Exercise 2 - level 1

When a user clicks the ALERT button, an alert box should pop up with the text "Thanks for visiting Bikes for Refugees!"

📝 Exercise 3 - level 1

Write JavaScript below that changes the background colour of the page when the "Change colour" button is clicked.

📝 Exercise 4 - level 1

When a user clicks the "Add some text" button, a new paragraph should be added below the buttons that says "Read more below."

📝 Exercise 5 - level 2

When the "Larger links!" button is clicked, the text of all links on the page should increase.

📝 Exericse 6 - level 2

When clicking the blue add button, take the text written in the input element, and add that text to the DOM. The text should be added using ul and li

📝 Exercise 7 - level 3

Clicking Donate Now should show a modal where a user can input some amount they want to donate to the cause. When they written the amount they should be able to click a button that will do the donation. When the donation has been completed. Show a success message and then close the modal.

📝 Exercise 8 - level 3

Your feature here. Come up with some feature you would like to create!

Taken from https://syllabus.codeyourfuture.io/js-core-2/week-2/lesson

Last updated