JavaScript beginner's guide
The JavaScript code starts with <script type="text/javascript"> and ends with </script>. It can be placed anywhere in the html document (in head or body section).
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello JavaScript World!");
//-->
</script>
<noscript>Your browser does not support JavaScript!</noscript>
</body>
</html>
If JavaScript is not supported by web browser, then all JavaScript
code will be displayed in browser’s window. To avoid such cases use
// JavaScript comment in combination with <!-- and --> which are
HTML comments.
Additionally, if scripts are not supported, display a message that
scripts are not supported in your browser.
When printing a string, you can use any HTML tag.
If you put JavaScript code in <head> tag, then it will be executed
automatically when page is loaded. If you put JavaScript code
somewhere inside <body> tag, than it is invoked on user’s request
(click or mouse-over).
JavaScript in external file
If script will be used on more than one page, it would be wise to put it in separate document (.js) instead of embedding the JavaScript code into html. The src argument of script tag must provide the path to script.
<html>
<head>
<script type="text/javascript" src="somescript.js">
</head>
<body>
</body>
</html>
Declaring variables
There is no need to declare a type of variable (int, String...).
var x = 2;
var firstname = "John";
var lastname = "Johnson";
document.write(firstname + " " + lastname);
Conditions
var date = new Date();
var hour = date.getHours();
if (hour < 12) {
document.write("Good morning");
} else {
document.write("Howdy partner");
}
var day = date.getDay();
switch (day) {
case 1:
document.write("monday");
break;
case 2:
document.write("tueseday");
break;
case 5:
document.write("friday");
break;
case 0:
document.write("sunday");
break;
default:
document.write("some day");
break;
}
Show alert box
<html>
<head>
<script type="text/javascript">
function showAlert()
{
alert("I am warning you!");
}
</script>
</head>
<body>
<input type="button" onclick="showAlert()" value="Show alert" />
</body>
</html>
Show confirmation dialog
<html>
<head>
<script type="text/javascript">
function showConfirm() {
var r=confirm("Choose something");
if (r==true) {
alert("OK seems reasonable choice.");
}
else {
alert("You cancelled me!");
}
}
</script>
</head>
<body>
<input type="button" onclick="showConfirm()" value="Confirm" />
</body>
</html>
Input text box
<html>
<head>
<script type="text/javascript">
function showPrompt() {
var name=prompt("Name","noone");
if (name!=null && name!="") {
document.write("Hello " + name);
}
}
</script>
</head>
<body>
<input type="button" onclick="showPrompt()" value="Show prompt box" />
</body>
</html>
Functions
It is not needed to declare what type of variable a function will return (void, String, int...).
function add(a, b) {
return a+b;
}
Loops
var i = 0;
for (i = 0; i < 5; i++) {
document.write("counter: " + i + "<br>");
}
var i = 0;
while (i < 5) {
document.write("counter: " + i + "<br>");
i++;
}
var i=0;
do {
document.write("counter: " + i + "<br>");
i++;
} while (i<5);
Iterating through a table
var x;
var names = new Array();
names[0] = "John";
names[1] = "Frank";
names[2] = "Lucy";
for (n in names) {
document.write(names[n] + "<br>");
}
Events
JavaScript can detect events within your web browser.
Every element in html can have event assigned to it which
invokes JavaScript, for example: mouse click, mouse-over,
page loading, input fields, submit buttons...
With event handling you can create great looking Dynamic
HTML pages (DHTML).
<html>
<head>
</head>
<body>
<label onmouseover="alert('I detected onMouseOver event');return false">TEXT</label>
</body>
</html>
Error handling
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try {
if (x>10) {
throw "Err1";
} else if (x<0) {
throw "Err2";
} else if (isNaN(x)) {
throw "Err3";
}
} catch(er) {
if (er=="Err1") {
alert("Error! The value is too high");
}
if (er=="Err2") {
alert("Error! The value is too low");
}
if (er=="Err3") {
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>
JavaScript is object oriented
Date is probably the second most common class to programmers (right after the String class).
Example 1:
var date = new Date();
var hour = date.getHours();
var day = date.getDay();
document.write("day: " + day + " hour: " + hour + "<br>");
Example 2:
var date = new Date(1234567890);
document.write("date: " + date.getHours());
Example 3:
var date = new Date(2010, 3, 12, 22, 25);
document.write("hours: " + date.getHours());
Creating custom object
Example 1:
var person = new Object();
person.name = "John";
person.eat = eat;
document.write(person.name);
person.eat();
function eat() {
document.write("I am eating");
}
Example 2:
function animal(name, age) {
this.name = name;
this.age = age;
this.eat = eat;
}
function eat() {
document.write("I am eating");
}
var a = new animal("Lucy", 20);
document.write(a.name);
a.eat();
Arrays
Example 1:
var names = new Array();
names[0] = "John";
names[1] = "Frank";
names[2] = "Lucy";
Example 2:
var names = new Array("John", "Frank", "Lucy");
Example 3:
var names = ["John", "Frank", "Lucy"];
Detecting browser
function detectBrowser() {
var browser = navigator.appName;
var browserVersion = navigator.appVersion;
alert("Your browser is: " + browser + " Version: " + browserVersion);
}
Timers
Start timer that periodically executes function 'myTimer' every 1000 ms.
var currentTime = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
Stop timer
clearInterval(currentTime);