Lecture 13 JavaScript Syntax and DOM
Reading: 7.1 - 7.4
Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.
7.2 - 7.4: JavaScript Syntax
7.1: Key JavaScript Concepts
7.2, 7.3, 7.4: JavaScript Syntax
Number
type
(7.2.2)
var enrollment = 99;
var medianGrade = 2.8;
var 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
Comments
(same as Java)
(7.2.4)
identical to Java's comment syntax
recall: 4 comment syntaxes
HTML: <!-- comment -->
CSS/JS/PHP: /* comment */
Java/JS/PHP: // comment
PHP: # comment
More about String
escape sequences behave as in Java:
\' \" \& \n \t \\
converting between numbers and String
s:
var count = 10;
var s1 = "" + count ;
var s2 = count + " bananas, ah ah ah!";
var n1 = parseInt ("42 is the answer");
var n2 = parseFloat("booyah");
accessing the letters of a String
:
var firstLetter = s[0] ;
var firstLetter = s.charAt(0) ;
var lastLetter = s.charAt(s.length - 1);
for
loop
(same as Java)
(7.2.8)
for (initialization ; condition ; update ) {
statements ;
}
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
Math object
(7.2.9)
var rand1to10 = Math.floor (Math.random() * 10 + 1);
var three = Math.floor (Math.PI );
methods:
abs
,
ceil
,
cos
,
floor
,
log
,
max
,
min
,
pow
,
random
,
round
,
sin
,
sqrt
,
tan
properties:
E
,
PI
Special values: null
and undefined
(7.2.10)
var ned = null;
var benson = 9;
var caroline;
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?
Logical operators
(7.3.1, 7.3.4)
> < >= <= && || ! == != === !==
most logical operators automatically convert types:
5 < "7"
is true
42 == 42.0
is true
"5.0" == 5
is true
===
and !==
are strict equality tests; checks both type and value
if/else
statement
(same as Java)
(7.3.2)
if (condition ) {
statements ;
} else if (condition ) {
statements ;
} else {
statements ;
}
identical structure to Java's if/else
statement
JavaScript allows almost anything as a condition
var iLike190M = true;
var ieIsGood = "IE6" > 0;
if ("web dev is great") { }
if (0) { }
any value can be used as a Boolean
"falsey" values: 0
, 0.0
, NaN
, ""
, null
, and undefined
"truthy" values: anything else
converting a value into a Boolean
explicitly:
var boolValue = Boolean( otherValue ) ;
var boolValue = !! (otherValue );
while
loops
(same as Java)
(7.3.5)
while (condition ) {
statements ;
}
do {
statements ;
} while (condition );
break
and continue
keywords also behave as in Java
alert("message ");
confirm("message ");
prompt("message ");
var name = [];
var name = [value , value , ..., value ];
name [index ] = value ;
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = [];
stooges[0] = "Larry";
stooges[1] = "Moe";
stooges[4] = "Curly";
stooges[4] = "Shemp";
two ways to initialize an array
length
property (grows as needed when elements are added)
var a = ["Stef", "Jason"];
a.push ("Brian");
a.unshift ("Kelly");
a.pop ();
a.shift ();
a.sort ();
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 back
unshift
and sh ift
add / remove from front
shift
and pop
return the element that is removed
Splitting strings:
split
and join
var s = "the quick brown fox";
var a = s.split (" ");
a.reverse();
s = a.join ("!");
split
breaks apart a string into an array using a delimiter
can also be used with regular expressions (seen later)
join
merges an array into a single string, placing a delimiter between them
Problems with JavaScript
JavaScript is a powerful language, but it has many flaws:
the DOM can be clunky to use
the same code doesn't always work the same way in every browser
code that works great in Firefox, Safari, ... will fail in IE and vice versa
many developers work around these problems with hacks (checking if browser is IE, etc.)
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"
type="text/javascript"></script>
the Prototype JavaScript library adds many useful features to JavaScript:
many useful
added methods to String, Array, Date, Number, Object
improves event-driven programming
many cross-browser compatibility fixes
makes easier (seen later)
The $
function
(9.1.3)
$("id ")
DOM element objects
(7.2.5)
every element on the page has a corresponding DOM object
access/modify the attributes of the DOM object with objectName .attributeName
DOM object properties
(7.2.5)
<div id="main" class="foo bar">
<p>Hello, <em>very</em> happy to see you!</p>
<img id="icon" src="images/borat.jpg" alt="Borat" />
</div>
Property
Description
Example
tagName
element's HTML tag
$("main").tagName
is "DIV"
className
CSS classes of element
$("main").className
is "foo bar"
innerHTML
content inside element
$("main").innerHTML
is "\n <p>Hello, <em>ve...
src
URL target of an image
$("icon").src
is "images/borat.jpg"
DOM properties for form controls
<input id="sid" type="text" size="7" maxlength="7" />
<input id="frosh" type="checkbox" checked="checked" /> Freshman?
Property
Description
Example
value
the text in an input control
$("sid").value
could be "1234567"
checked
whether a box is checked
$("frosh").checked
is true
disabled
whether a control is disabled (boolean)
$("frosh").disabled
is false
readOnly
whether a text box is read-only
$("sid").readOnly
is false
Abuse of innerHTML
var paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href="page.html">link</a>" ;
innerHTML
can inject arbitrary HTML content into the page
however, this is prone to bugs and errors and is considered poor style
we forbid using innerHTML
to inject HTML tags; inject plain text only
(later, we'll see a better way to inject content with HTML tags in it)
Adjusting styles with the DOM
(8.2.2)
<button id="clickme">Color Me</button>
window.onload = function() {
document.getElementById("clickme").onclick = changeColor;
};
function changeColor() {
var clickMe = document.getElementById("clickme");
clickMe.style.color = "red";
}
Color Me
Property
Description
lets you set any CSS style property for an element
contains same properties as in CSS, but with camelCasedNames
examples: backgroundColor
, borderLeftWidth
, fontFamily
Common DOM styling errors
many students forget to write .style
when setting styles
var clickMe = document.getElementById("clickme");
clickMe.color = "red";
clickMe.style .color = "red";
style properties are capitalized likeThis
, not like-this
clickMe.style.font-size = "14pt";
clickMe.style.fontSize = "14pt";
style properties must be set as strings, often with units at the end
clickMe.style.width = 200;
clickMe.style.width = "200px" ;
clickMe.style.padding = "0.5em" ;
write exactly the value you would have written in the CSS, but in quotes