2 Introduction Javascript Development
2 Introduction Javascript Development
JavaScript Development
The Magic of Dynamic Web Pages
Table of Contents
Intro to JavaScript
History
JavaScript in Web Pages
JavaScript Syntax
Pop-up boxes
Debugging in JavaScript
2
JavaScript
Dynamic Behavior in a Web Page
JavaScript
JavaScript is a front-end scripting language
developed by Netscape for dynamic content
Lightweight, but with limited capabilities
Can be used as object-oriented language
Embedded in your HTML page
Interpreted by the Web browser
Client-side, mobile and desktop technology
Simple and flexible
Powerful to manipulate the DOM
4
JavaScript Advantages
JavaScript allows interactivity such as:
Implementing form validation
React to user actions, e.g. handle keys
Changing an image on moving mouse over it
Sections of a page appearing and disappearing
Content loading and changing dynamically
Performing complex calculations
Custom HTML controls, e.g. scrollable table
Implementing AJAX functionality
5
What Can JavaScript Do?
Can handle events
Can read and write HTML elements and modify
the DOM tree
Can validate form data
Can access / modify browser cookies
Can detect the user’s browser and OS
Can be used as object-oriented language
Can handle exceptions
Can perform asynchronous server calls (AJAX)
6
The First Script
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
7
Using JavaScript Code
The JavaScript code can be placed in:
<script> tag in the head
<script> tag in the body - not recommended
External files, linked via <script> tag the head
Files usually have .js extension
<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
Highly recommended
The .js files get cached by the browser
8
JavaScript – When is Executed?
JavaScript code is executed during the page
loading or when the browser fires an event
All statements are executed at page loading
Some statements just define functions that can
be called later
Function calls or code can be attached as
"event handlers" via tag attributes
Executed when the event is fired by the browser
<img src="logo.gif" onclick="alert('clicked!')" />
9
Calling a JavaScript Function
from Event Handler – Example
<html>
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
10
Using External Script Files
Using external script files:
<html> external-JavaScript.html
<head>
<script src="sample.js" type="text/javascript">
</script>
</head> The <script> tag is always empty.
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
Confirmation box
Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
Prompt box
Contains text, input field with default value:
prompt ("enter amount", 10);
14
The Built-In
Browser Objects
Built-in Browser Objects
The browser provides some read-only data via:
window
The top node of the DOM tree
Represents the browser's window
document
holds information the current loaded document
screen
Holds the user’s display properties
browser
Holds information about the browser
16
DOM Hierarchy – Example
window
form form
button form
17
Opening New Window – Example
window.open()
window-open.html
var newWindow = window.open("", "sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");
newWindow.document.write(
"<html><head><title>
Sample Title</title>
</head><body><h1>Sample
Text</h1></body>");
newWindow.status =
"Hello folks";
18
The Navigator Object
alert(window.navigator.userAgent);
19
The Screen Object
The screen object contains information about
the display
window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);
20
Document and Location
document object
Provides some built-in arrays of specific objects
on the currently loaded Web page
document.links[0].href = "yahoo.com";
document.write(
"This is some <b>bold text</b>");
document.location
Used to access the currently open URL or
redirect the browser
document.location = "http://www.yahoo.com/";
21
Built-In Browser Objects
Live Demo
Other JavaScript Objects
The Math Object
The Math object provides some mathematical
functions
math.html
for (i=1; i<=20; i++) {
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write(
"Random number (" +
i + ") in range " +
"1..10 --> " + x +
"<br/>");
}
24
The Date Object
The Date object provides date / calendar
functions
dates.html
var now = new Date();
var result = "It is now " + now;
document.getElementById("timeField")
.innerText = result;
...
<p id="timeField"></p>
25
Timers: setTimeout()
Make something happen (once) after a fixed
delay
clearTimeout(timer);
clearInterval(timer);
27
Timer – Example
timer-demo.html
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
document.getElementById("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
28
Debugging JavaScript
Debugging JavaScript
Modern browsers have JavaScript console
where errors in scripts are reported
Errors may differ across browsers
Several tools to debug JavaScript
Microsoft Script Editor
Add-on for Internet Explorer
Supports breakpoints, watches
JavaScript statement debugger; opens the script
editor
30
Firebug
Firebug – Firefox add-on for debugging
JavaScript, CSS, HTML
Supports breakpoints, watches, JavaScript
console editor
Very useful for CSS and HTML too
You can edit all the document real-time: CSS,
HTML, etc
Shows how CSS rules apply to element
Shows Ajax requests and responses
Firebug is written mostly in JavaScript
31
Firebug (2)
32
JavaScript Console Object
The console object exists only if there is a
debugging tool that supports it
Used to write log messages at runtime
Methods of the console object:
debug(message)
info(message)
log(message)
warn(message)
error(message)
33