Web Programming Step by Step

Lecture 12
Introduction to JavaScript

Reading: 7.1 - 7.4

Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

7.1: Key JavaScript Concepts

Client-side scripting (7.1.1)

client-side scripting

Why use client-side programming?

PHP already allows us to create dynamic web pages. Why also use client-side scripting?

What is JavaScript? (7.1)

JavaScript vs. Java

Java + mary jane, da endo, aight = JavaScript

JavaScript vs. PHP

JS <3 php

Linking to a JavaScript file: script

<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>

A JavaScript statement: alert

alert("IE6 detected.  Suck-mode enabled.");

Variables and types (7.2.1, 7.2.3)

var name = expression;
var age = 32;
var weight = 127.4;
var clientName = "Connie Client";

String type (7.2.7)

var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" "));   // "Connie"
var len = s.length;                           // 13
var s2 = 'Melvin Merchant';                   // can use "" or ' '

Event-driven programming


Buttons: <button>

the canonical clickable UI control (inline)

<button>Click me!</button>

JavaScript functions

function name() {
	statement ;
	statement ;
	statement ;
function myFunction() {
	alert("How are you?");

Event handlers

<element attributes onclick="function();">...
<button onclick="myFunction();">Click me!</button>

Document Object Model (DOM) (7.1.4)

a set of JavaScript objects that represent each element on the page


DOM element objects (7.2.5)

dom object

Accessing elements: document.getElementById

var name = document.getElementById("id");
<button onclick="changeText();">Click me!</button>
<input id="output" type="text" value="replace me" />
function changeText() {
	var textbox = document.getElementById("output");
	textbox.value = "Hello, world!";

More advanced example

<button onclick="swapText();">Click me!</button>
<span id="output2">Hello</span>
<input id="textbox2" type="text" value="Goodbye" />
function swapText() {
	var span = document.getElementById("output2");
	var textBox = document.getElementById("textbox2");
	var temp = span.innerHTML;
	span.innerHTML = textBox.value;
	textBox.value = temp;