JavaScript and DOM Manipulation
CSCI 344: Advanced Web Technologies
Fall 2024
1
Announcements
2
Outline
3
Outline
4
Client-Side JavaScript
5
Nice overview: https://javascript.info/intro
“Client-Side” JavaScript
What is JavaScript’s job within the browser?
6
Nice overview: https://javascript.info/intro
“Client-Side” JavaScript (Continued)
What is JavaScript’s job within the browser?
7
Nice overview: https://javascript.info/intro
Possibilities and Limitations of “Client-Side” JavaScript
8
Nice overview: https://javascript.info/intro
Possibilities and Limitations of “Client-Side” JavaScript
9
Nice overview: https://javascript.info/intro
Outline
10
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
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
...
1 <body>
2 <div class=”title-bar”>
3 <h1>Welcome, Malik</h1>
4 <img id=”profile” src=”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;
}
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 |
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
Quiz: Q2. Do these methods return the same thing?
document.querySelector('#photo-gallery')
document.getElementById('photo-gallery')
16
YES!
Quiz: Q3. Do these methods return the same thing?
document.querySelectorAll('.red-text')
document.getElementsByClassName('red-text')
17
YES!
Quiz: Q4. Do these methods return the same thing?
document.querySelectorAll('img')
document.getElementsByTagName('img')
18
YES!
And once you target an element, �you can change stuff...
19
Outline
20
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
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=”profile” src=”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
Step 2: Specify what you want to change
Once you target an element, you can change the element’s…
23
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”; |
... | ... |
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"; |
... | ... |
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 |
Let’s do some exercises using the �DOM Manipulation Tester
Summary of the Process of DOM Manipulation
28
Outline
29
Event Listeners
When JavaScript is used in HTML pages, JavaScript can "react" to particular “events,” which include (among others):
Event Listeners provide a way of “listening” and responding to events.
30
What are Event Handlers?
31
But how do you create an event handler?
There are several ways to attach functions to events in client-side Javascript:
32
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
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
The Event Object
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
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
Outline
38
Strings and Template Literals
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)
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
ES6 Introduced a better way: Client-side templates
` <template goes here> `
${ my_expression }
42
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>`;
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
Outline
45
Practice Time
Download the Lecture 9 Code
46
Activity 1: Manipulating Style Properties
Open 01-style-property-demo
47
Activity 2: Manipulating HTML Element Attributes
Open 02-attribute-demo
48
Activity 3: Together
Open 03-all-of-the-above
49
More Practice: Loops and Templates