HW 2 is out (layouts and flexboxes): Due Wednesday (October 11th)
Part 2 of the Creative Project is due tonight. I have office hours in CSE 216 right after lecture! Great work so far :)
How to write content for a webpage using HTML
How to add styles to a webpage using CSS
and linking a CSS
file to an
HTML
file
How to inspect the HTML
and CSS
of web pages in the browser
Now that we know how to add content and styles to a web page, let's explore how to add responsive behavior
This lecture we'll cover the basics of the JavaScript language:
Later this week we'll use these building blocks to learn how to dynamically update what you see on a web page in response to clicks, text input, timers, etc.
Client-side script: Code runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.
A lightweight programming language ("scripting language")
Created in 1995 (over 10 days) by Brendan Elch (originally called Mocha then LiveScript)
Used to make web pages interactive:
A web standard (but not supported identically by all browsers)
NOT related to Java other than name and some syntactic similarities...
Can be used in the browser, Adobe Acrobat, Adobe Photoshop, embedded computers, the Unix terminal, etc. (we will be using it in the browser)
Interpreted, not compiled (huh?)
More relaxed syntax and rules
JavaScript's key construct is the function rather than the object/class.
Contained within a web page and integrates with its HTML/CSS
content
<script>
The script
tag should be placed in the HTML
page's
head
Script code is stored in a separate .js
file
JS code can be placed directly in the HTML
file's body
or head
(like CSS
)
alert
alert("message");
alert("IE6 detected. Suck-mode enabled.");
A JS command that pops up a dialog box with a message
let name = expression;
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
Variables are declared with the let
keyword (case-sensitive). You may also see var
used instead of let
- this is an older convention, and you should use let
in this class.
Types are not specified, but JS does have types ("loosely-typed")
Number
, Boolean
, String
,
Array
, Object
, Function
, Null
,
Undefined
let enrollment = 99;
let mediangrade = 2.8;
let credits = 5 + 4 + (2 * 3);
Integers and real numbers are the same type (no int
vs. double
)
Same operators: + - * / % ++ -- = += -= *= /= %=
Similar precedence to Java
Many operators auto-convert types: "2" * 3
is 6
let nickName = "Sparky O'Sparkz"; // "Sparky O'Sparks"
let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
let len = nickName.length; // 15
let name = 'Pikachu'; // can use " " or ' '
Methods:
charAt
,
charCodeAt
,
fromCharCode
,
indexOf
,
lastIndexOf
,
replace
,
split
,
substring
,
toLowerCase
,
toUpperCase
charAt
returns a one-letter String
(there is no
char
type)length
is a property (not a method, as it is in Java)
Concatenation with +
: 1 + 1
is 2
, but "1" + 1
is "11"
Practice: repeat
, containsTwice
Escape sequences behave as in Java: \' \" \& \n \t \\
To convert between numbers and Strings
:
let count = 10; // 10
let stringedCount = "" + count; // "10"
let puppyCount = count + " puppies, yay!"; // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?"); // NaN
To access characters of a String s
, use s[index]
or
s.charAt(index)
:
let firstLetter = puppyCount[0]; // "1"
let fourthLetter = puppyCount.charAt(3); // "p"
let lastLetter = puppyCount.charAt(puppyCount.length - 1); // "!"
// single-line comment
/* multi-line comment */
Identical to Java's comment syntax
Recall: 3 comment syntaxes
HTML: <!-- comment -->
CSS/Java/JS: /* comment */
Java/JS: // comment
Practice:
commentSyntax
,
commentary
for loop
(same as Java)
for (initialization; condition; update) {
statements;
}
let sum = 0;
for (let i = 0; i < 100; i++) {
sum = sum + i; // same as sum += i;
}
let s1 = "It's a-me, Mario!";
let s2 = "";
for (let i = 0; i < s.length; i++) {
s2 += s1[i] + s1[i];
}
// s2 stores "IItt''ss aa--mmee,, MMaarriioo!!"
let rand1to10 = Math.floor(Math.random() * 10 + 1);
let three = Math.floor(Math.PI);
Methods: abs
,
ceil
,
cos
,
floor
,
log
,
max
,
min
,
pow
,
random
,
round
,
sin
,
sqrt
,
tan
Properties: E
, PI
Relational: > < >= <=
Logical: && || !
Equality: == != === !==
5 < "7"
42 == 42.0
"5.0" == 5
===
and !==
are strict equality tests; checks both
type and value: "5.0" === 5
is false
let iLikeJS = true;
let ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ }
Any value can be used as a Boolean
0
, 0.0
, NaN
,
""
, null
, and undefined
Converting a value into a Boolean
explicitly:
let boolValue = Boolean(otherValue);
let boolValue = !!(otherValue);
null
and undefined
let foo = null;
let bar = 9;
let baz;
/* At this point in the code,
* foo is null
* bar is 9
* baz is undefined
*/
undefined
: has not been declared, does not exist
null
: exists, but was specifically assigned an empty or null
value
Why does JavaScript have both of these?
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Identical structure to Java's if/else
statements
JavaScript allows almost anything as a condition
Practice:
rockPaperScissors
while (condition) {
statements;
}
do {
statements;
} while (condition);
break
and continue
keywords also behave as in Java but do not
use them in this class!
Practice:
loopMystery6
let name = []; // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value; // store element
let types = ["Electric", "Water", "Fire"];
let pokemon = []; // []
pokemon[0] = "Pikachu"; // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]
Two ways to initialize an array
length
property (grows as needed when elements are added)
let a = ["Mario", "Luigi"]; // [Mario, Luigi]
a.push("Koopatroopa"); // [Mario, Luigi, Koopatroopa]
a.unshift("Bowser"); // [Bowser, Mario, Luigi, Koopatroopa]
a.pop(); // [Bowser, Mario, Luigi]
a.shift(); // [Mario, Luigi]
a.sort(); // [Luigi, Mario]
Array serves as many data structures: list, queue, stack, ...
Methods: concat
,
join
,
pop
,
push
,
reverse
,
shift
,
slice
,
sort
,
splice
,
toString
,
unshift
push
and pop
add/remove from backshift
and unshift
add/remove from frontshift
and pop
return the element that is removed
Practice:
findMin
,
switchPairs
split
and join
let s = "the quick brown fox";
let a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
split
breaks apart a String into an array using a delimiter
let a = s.split(/[ \t]+/);
join
merges an array into a single String, placing a delimiter between
them
function name() {
statement;
statement;
...
statement;
}
function myFunction() {
alert("Hello!");
alert("Your browser says hi!");
}
The above could be the contents of example.js
linked to our
HTML
page
Statements placed into functions can be evaluated in response to user events
Practice: functionMystery1
, sumUpTo
, veryBestSong
Unlike Java programs, JS programs have no main
; they respond to user actions
called events
Event-Driven Programming: writing programs driven by user events
<element attributes onclick="function();">...
<div onclick="myFunction();">Click me!</div>
JavaScript functions can be set as event handlers
When you interact with the element, the function will execute
onclick is just one of many event HTML
attributes we'll use
<button>
<button onclick="myFunction();">Click me!</button>
Button's text appears inside tag; can also contain images
To make a responsive button or other UI control:
document.getElementById
let name = document.getElementById("id");
document.getElementById
returns the DOM object for an element with a given id
(note that you omit the #
when giving an id)
document.getElementById
: An Example
<img id="pokeball" src="images/pokeball.jpg" alt="a pokeball" />
<button onclick="changeImage();">Click me!</button>
function changeImage() {
let pokeballImg = document.getElementById("pokeball");
pokeballImg.src = "images/mystery.gif";
}
A common use for JavaScript on webpages is for event-handling and form validation.
To use form validation, we need to learn about a few more HTML tags...
<input>
<!-- 'q' happens to be the name of Google's required paramter -->
<input type="text" name="q" value="Colbert Report" />
<input type="submit" value="Booyah!" />
Input element is used to create many UI controls (an inline element that must be self-closed
name
attribute specifies name of query parameter to pass to server
type
can be button
, checkbox
, file
, hidden
, password
, radio
, reset
, submit
, text
, ...
value
attribute specifies control's initial text
<input>
text fields
<input type="text" size="10" maxlength="8" /> NetID <br />
<input type="password" size="16" /> Password
<input type="submit" value="Log In!" />
input
attributes: disabled
, maxLength
, readonly
, size
, value
size
attribute controls onscreen width of text field
maxlength
limits how many characters the user is able to type into the field
<textarea>
<textarea rows="4" cols="20">
Type your comments here.
</textarea>
Initial text is placed inside textarea
tag (optional)
Required rows
and cols
attributes specify height/width in characters
optional readonly
attribute means text cannot be modified
Review programming basics: using variables, arrays, loops, if-statements, and functions
Go over some JavaScript tutorials - there are many great ones!
Practice! We now have JavaScript problems on Practice-It (80+ problems) and its sister site CodeStepByStep (200+ problems).
Check out cool examples of JavaScript on the web!