Introduction To JS
Introduction To JS
HTML
script tag should be placed in 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)
but this is bad style (should separate
content, presentation, and behavior
Event-driven programming
8
HTML
<button onclick="myFunction();">Click me!</button>
HTML
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
but popping up an alert window is
disruptive and annoying
Document Object Model
14
(DOM)
most JS code
manipulates elements
on an HTML page
we can examine
elements' state
e.g. see whether a box
is checked
we can change state
e.g. insert some new
text into a div
we can change styles
DOM element objects
15
Accessing elements:
16
document.getElementById
var name = document.getElementById("id");
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
}
JS
Accessing elements:
17
document.getElementById
document.getElementById returns the
DOM object for an element with a given
id
can change the text inside most
elements by setting the innerHTML
property
can change the text in form controls by
setting the value property
Changing element style:
18
element.style
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
Preetify
19
function changeText() {
//grab or initialize text here
// single-line comment
/* multi-line comment */
JS
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS
Popup boxes
28
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS