Lecture 08
Lecture 08
Web Programming
Fundamentals
Spring 2017
Victoria Kirst
([email protected])
Today's schedule
Wednesday
- DOM: How to interact with your web page
- HW1 due tonight
- HW2 is out!
- Victoria's Office Hours → moved to Friday again
- Amy and Cindy have office hours at 4pm like usual
Friday
- More DOM
- data attributes
- Browser extensions
- Victoria's Office Hours from 2:30 to 4pm
var, let, const
But if you use var, the variable exists for the entirety of the
function, completely independent of blocks:
if (...) {
var x = 5;
...
}
// x is 5 here
This is the same behavior as Python, which also has
function scope.
* Note that variable hoisting and function scope are not the same thing, either.
Blocks and scope
But if you use var, the variable exists for the entirety of the
function, completely independent of blocks:
if
For(...)
more { details, come to office hours!
var x = 5;
... In 193X we encourage you
}
to always use let and const,
// x is 5 here
so you don't need to understand
This is the same behavior as Python, which also has
var very deeply anyway.
function scope.
* Note that variable hoisting and function scope are not the same thing, either.
JavaScript
language tour
Arrays
- 0-based indexing
- Mutable
- Can check size via length property (not function)
Looping through an array
const scores = {
peach: 100,
mario: 88,
luigi: 91
};
console.log(scores['peach']); // 100
console.log(scores.luigi); // 91
Maps through Objects
Example:
Here is a UI element that
Click Me!
the user can interact with.
Event-driven programming
Click Me!
EVENT!
Click Me!
Buttons:
<html>
<head>
<title></title>
</head>
<body>
<h1></h1>
<div>
<p></p>
</div>
</body>
</html>
The DOM
document.querySelector('css selector');
- Returns the first element that matches the given CSS selector.
document.querySelectorAll('css selector');
- Returns all elements that match the given CSS selector.
Getting DOM objects
function onClick() {
console.log('clicked');
}
function onClick() {
console.log('clicked');
}
function onClick() {
console.log('clicked');
}
function onClick() {
console.log('clicked');
}
You can add the defer attribute onto the script tag so that
the JavaScript doesn't execute until after the DOM is
loaded (mdn):
You can add the defer attribute onto the script tag so that
the JavaScript doesn't execute until after the DOM is
loaded (mdn):
HTML
<img src="puppy.png" />
JavaScript
const element = document.querySelector('img');
element.src = 'bear.png';
(More on classList)
Example: Present
(Programming note: I got these mixed up in lecture and used target when I
meant currentTarget, so I'm correctly the slides retroactively. Whoops,
sorry!)
Example: Present
It would be nice to
change the text after the
present is "opened"...
Some properties of Element objects
Property Description
document.createElement(tag string)
element.appendChild(element);
element.remove();