1 of 50

JavaScript and DOM Manipulation

CSCI 344: Advanced Web Technologies

Fall 2024

1

2 of 50

Announcements

  1. HW2 – due Friday at midnight
  2. Tutorial 5 – due Monday at midnight
  3. Quiz 1 on Monday – during class

2

3 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

3

4 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

4

5 of 50

Client-Side JavaScript

  1. JavaScript can be run anywhere that a JavaScript engine is installed
  2. However, JavaScript DOM manipulation only happens in the browser.
  3. Nothing covered in this lecture will work in Node.js

5

6 of 50

“Client-Side” JavaScript

What is JavaScript’s job within the browser?

  1. Can respond to user events
  2. Can manipulate the DOM by adding/removing/modifying/deleting:
    1. elements
    2. attributes
    3. style properties
    4. content
  3. Can pull down resources from any server (for which it is authorized) and inject content into the DOM

6

7 of 50

“Client-Side” JavaScript (Continued)

What is JavaScript’s job within the browser?

  1. Can post content from the browser to a server
  2. Can manipulate data (usually represented as a lists of objects)
  3. Can do all the computations that an ordinary language can do (but heavy computations are typically delegated to server processes)

7

8 of 50

Possibilities and Limitations of “Client-Side” JavaScript

  • Can JavaScript from your browser access your file system?
    1. Kind of – it can access the area of memory allocated for temporary data and variables (cookies, local storage, etc.).
    2. It can’t access the rest of your file system. That’d be a huge security risk!
  • Can JavaScript access your camera, microphone, or current location?
    • Only with your permission
  • Can JavaScript store information about you that the site can access later?
    • Yes – Cookies and localstorage (you can view these via the browser inspector)

8

9 of 50

Possibilities and Limitations of “Client-Side” JavaScript

  • Can JavaScript transmit information about your browsing interactions back to the server?
    1. Yes — b/c JavaScript can (1) “listen” to any user event (mousemove, click, drag, scroll, etc.), and (2) post information to a server, it can collect and transmit fine-grained information about your browsing behavior
  • Can any website access the information that another website has gathered about you?
    • Not from the browser. That can only be done when two servers from different companies collude to share data (often through a third-party ad network).

9

10 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

10

11 of 50

Document Object Model (DOM)

Reminder: the DOM is way of representing a document, like a web page, in a way that can be understood by a human and by a computer. Javascript can directly manipulate the DOM dynamically.

11

12 of 50

Selectors

Recall from CSS: selectors are ways of targeting elements in a web page so that we can apply styles to them.

Remember these...

12

13 of 50

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

body {

color: grey;

}

h1, li {

text-transform: uppercase;

display: inline-block;

color: #999999;

}

.title-bar {

padding: 5px;

background-color: #EEEEEE;

}

#profile {

width: 100px;

float: left;

margin-right: 20px;

}

14 of 50

JavaScript also supports element targeting!

JavaScript’s document object has several built-in methods that take selectors as arguments. The first three were part of the original language. The last two are new (with ES6).

14

Method

Example

Returns

getElementById()

document.getElementById("my_element")

single element

getElementsByTagName()

document.getElementsByTagName("div")

list of elements

getElementsByClassName()

document.getElementsByClassName("panel")

list of elements

querySelector()

document.querySelector("#my_element")

document.querySelector("p")

document.querySelector(“.my-announcements")

single element

querySelectorAll()

document.querySelectorAll("p")

list of elements

15 of 50

Quiz: Q1. Do these methods return the same thing?

document.querySelector('div')

document.querySelectorAll('div')

15

NO! The first returns a single element, the second returns a list of elements

16 of 50

Quiz: Q2. Do these methods return the same thing?

document.querySelector('#photo-gallery')

document.getElementById('photo-gallery')

16

YES!

17 of 50

Quiz: Q3. Do these methods return the same thing?

document.querySelectorAll('.red-text')

document.getElementsByClassName('red-text')

17

YES!

18 of 50

Quiz: Q4. Do these methods return the same thing?

document.querySelectorAll('img')

document.getElementsByTagName('img')

18

YES!

19 of 50

And once you target an element, �you can change stuff...

19

20 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

20

21 of 50

Summary of the Process of DOM Manipulation

Step 1: Target an element using one of the selector methods.

Step 2: Specify what you want to change about the element.

21

22 of 50

Step 1: Element Targeting

To target an element, use the document.querySelector method.

Examples:

document.querySelector("#profile");

document.querySelector("div");

document.querySelector(".title-bar");

document.querySelector("body");

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

22

23 of 50

Step 2: Specify what you want to change

Once you target an element, you can change the element’s…

  1. attributes (e.g., class, href, src, alt)
  2. style properties (e.g., width, height, borderRadius, backgroundColor)
  3. Inner HTML (what goes inside of the element)

23

24 of 50

2a. Attribute Manipulation

Examples of attributes you can manipulate…

24

Attribute

Example

className

myElement.className = “panel";

innerHTML

myElement.innerHTML = “hi!";

src (for images)

myElement.src = “some_image_url”

href (for links)

myElement.href = “http://site.com”;

...

...

25 of 50

2b. Style Property Manipulation

These are but a few. You can set any style property using JavaScript

25

Property

Example

width

myElement.style.width = "200px";

height

myElement.style.height = "200px";

background color

myElement.style.backgroundColor = "hotpink";

border width

myElement.style.borderWidth = "5px";

padding

myElement.style.padding = "10px";

display

myElement.style.display = "none";

...

...

26 of 50

Footnote: Other Selection Methods

There are also other selection methods you can also use! But querySelector is the most versatile!

26

Method

Example

Returns

querySelector()

document.querySelector("#my_element")

document.querySelector("p")

document.querySelector(“.my-announcements")

single element

querySelectorAll()

document.querySelectorAll("p")

list of elements

getElementById()

document.getElementById("my_element")

single element

getElementsByTagName()

document.getElementsByTagName("div")

list of elements

getElementsByClassName()

document.getElementsByClassName(".panel")

list of elements

27 of 50

Let’s do some exercises using the �DOM Manipulation Tester

28 of 50

Summary of the Process of DOM Manipulation

  1. Target an element using one of the selector methods.
    • For now, let’s use document.querySelector()
  2. Specify what you want to change about the element:
    • A style property?
    • An attribute?
    • An element’s inner HTML?
  3. Also note: DOM manipulation typically happens in response to an event.

28

29 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

29

30 of 50

Event Listeners

When JavaScript is used in HTML pages, JavaScript can "react" to particular “events,” which include (among others):

  • onchange
  • onclick
  • onmouseover
  • onmouseout
  • onkeydown
  • onload

Event Listeners provide a way of “listening” and responding to events.

30

31 of 50

What are Event Handlers?

  1. Recall: a function is an encapsulated group of programming statements that you can invoke on demand.
    • They can take arguments
    • They can return data
  2. An event is an action that your browser can detect. Examples include: mouseover, mouseout, click, scroll, and drag
  3. An event listener allows you to specify a function to call when an event fires.
  4. An event handler is the function that responds to an event

31

32 of 50

But how do you create an event handler?

There are several ways to attach functions to events in client-side Javascript:

  1. The Hybrid Approach: HTML + JavaScript (hybrid example)
  2. The “just JavaScript” approach (just javascript example)

32

33 of 50

Event Handler Example: Hybrid Approach

HTML (connect the function to the event):

<button id="btn1" onclick="sayHello()">Say Hello</button>

<button id="btn2" onclick="sayGoodbye()">Say Goodbye</button>

JS (define the function):

const sayHello = () => {� alert('Hello!');

};�

const sayGoodbye = () => {� alert('Bye!');�};

33

34 of 50

Event Handler Example: “Just JavaScript” Approach

HTML (connect the function to the event):

<button id="btn1">click me</button>

<button id="btn2">click me</button>

JS (define the function):

const sayHello = () => {� alert('Hello!');

};�

const sayGoodbye = () => {� alert('Bye!');�};

// attach event handlers using JavaScript

document.querySelector('#btn1').addEventListener('click', sayHello);

document.querySelector('#btn2').addEventListener('click', sayGoodbye);

34

35 of 50

The Event Object

  1. If event listeners are defined via JavaScript, they pass one argument – an event object that captures metadata about the event that just happened.
  2. One property of the event object we’re going to use is the currentTarget, which corresponds to the element that triggered the event.
  3. One common technique in front-end programming is to embed data attributes – which is a way of storing information that can be used later by various event handlers.
    1. Data attributes have a data- prefix

36 of 50

Example: Contextual Event Handler

HTML:

<button id="button1" data-color="teal" data-message="Good afternoon!">Button 1</button>

JavaScript is aware of the element the user clicked and responds accordingly:

const changeColor = (ev) => {

const domElement = ev.currentTarget;

document.querySelector('body').style.background = domElement.dataset.color;

};

document.querySelector('#button1).addEventListener('click', changeColor);

document.querySelector('#button2).addEventListener('click', changeColor);

document.querySelector('#button3).addEventListener('click', changeColor);

36

37 of 50

Example: Contextual Event Handler

Functionality depends on which element was clicked:

// event handler:�const changeColor = (ev) => {� console.log(ev);� const sourceElement = ev.currentTarget; // detects the element the user clicked� document.querySelector('body').style.background = sourceElement.innerHTML;�};

// event listener attach to all of the buttons:�document.querySelector('#color1').addEventListener('click', changeColor);

document.querySelector('#color2').addEventListener('click', changeColor);�document.querySelector('#color3').addEventListener('click', changeColor);

37

38 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

38

39 of 50

Strings and Template Literals

  • One of the most common tasks in JavaScript is to build parts of an interface using strings.
  • Moreover, these strings are typically generated from server data.
  • Because of this, you need to do a lot of string concatenation:
    • document.querySelector("div").innerText = "<p>" + name + "</p>";
  • Because this gets syntactically overwhelming fast, template literals were introduced in ES6.

40 of 50

Data → HTML

const player = {

name: "Jane",

pic: "http://website.com/avatar.png",

score: 300

};

<div class="card">

<img src="http://website.com/avatar.png">

<p>Jane scored 300 points</p>

</div>

The Data

The HTML�(Goal)

41 of 50

You COULD do one big string concatenation...

...but string concatenation is annoying – difficult to read and easy to make mistakes.

const html = '<div class="card">' +

'<img src="' + player.pic + '">' +

'<p>' + player.name + ' scored ' +

player.score + ' points</p>' +

'</div>';

41

42 of 50

ES6 Introduced a better way: Client-side templates

  • Templates, or “template literals” are strings that allow you to embedded expressions
  • They’re convenient for generating larger chunks of HTML from lists of objects
  • Uses the “backtick” character (instead of regular single or double quotes) to indicate that you are specifying a template (above the tab key):

` <template goes here> `

  • Within the template, expressions represented like this:

${ my_expression }

42

43 of 50

Rewriting previous HTML using template syntax

const html = `

<div class="card">

<img src="${player.pic}">

<p>

${player.name}'s high score is:

${player.score}

</p>

</div>`;

44 of 50

More on templates

const name = 'Walter';

console.log( ` A template

can be multiple lines.

It can also evaluate expressions like:

${2 + 2} or� ${name} or

${getTodaysDate()}

` );

44

45 of 50

Outline

  • Intro to Client-Side JavaScript
  • Selectors & element targeting
  • DOM manipulation
  • Event handlers
  • Strings and template literals
  • Practice

45

46 of 50

Practice Time

Download the Lecture 9 Code

46

47 of 50

Activity 1: Manipulating Style Properties

Open 01-style-property-demo

  1. Modify each of the event handlers so that when the button is clicked, the body’s background color changes to the corresponding color.
  2. How would you switch the font of the h1 tag when the user clicks on the button?

47

48 of 50

Activity 2: Manipulating HTML Element Attributes

Open 02-attribute-demo

  1. Modify each of the event handlers so that when the image’s “src” attribute is set to a different animal image.
  2. How would you also modify the paragraph text when each button is clicked?

48

49 of 50

Activity 3: Together

Open 03-all-of-the-above

  • Update the body of the changeColor() function so that the panel turns to hotpink.
  • Update the body of the changeTitle() function so that it changes the title of the webpage to "hi there!"
  • Update the body of the addImage() function so that it adds an image of a cat to each panel
  • update the body of the clearDivs() function so that it clears out the image of a wombat for each panel

49

50 of 50

More Practice: Loops and Templates

  • practice/04-create-cards-from-list-of-objects
    • Loop through the people array and create a card for all of the players.
    • Create a function that generates a card from a template
    • Use a for…of to: (a) generate a template for each person and (b) insert the rendered template into the DOM�
  • practice/05-photo-gallery
    • See instructions in index.js