Académique Documents
Professionnel Documents
Culture Documents
(MoCU)
Faculty:
Programme:
BScBICT II
Course:
Scripting Language.
Course Ante:
CIT 204
Instructor Name:
Mr. G Kinyatta.
Name:
Matokeo Msavange
Reg No:
FBIS/BScBICT/084/13.
Theme:
Date:
TABLE OF CONTENTS
Table of Content..2
To explain the Following Concept as used in JavaScript Language ........................................ 4
CHAPTER ONE ........................................................................................................................................... 4
1.0 JavaScript Introduction ........................................................................................................................... 4
CHAPTER TWO .......................................................................................................................................... 4
2.0 Conditional Statements ........................................................................................................................... 4
JavaScript is different from the Java language (developed in the 1990s at Sun Microsystems).
However, the two languages can interoperate well. Client-side JavaScript programs, or scripts,
can be embedded directly in HTML source of Web pages. Depending on the Web developer's
intent, script code may run when the user opens the Web page, clicks or drags some page
element with the mouse, types something on the keyboard, submits a form, or leaves the page.
CHAPTER TWO
2.0 Conditional Statements
Conditional statements are used to perform different actions based on different conditions. Very
often in writing JavaScript code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this. JavaScript supports conditional
statements which are used to perform different actions based on different conditions
In JavaScript there are the following conditional statements:
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
The value of the expression is compared with the values of each case.
NB: The above codes and output specifies the day for which the codes was execute
CHAPTER THREE
3.0 JavaScript Loops
Loops can execute a block of code a number of times. Loops are handy, if you want to run the
same code over and over again, each time with a different value. Often this is the case when
working with arrays. Looping control flow allows us to go back to some point in the program
where we were before and repeat it with our current program state.
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
do/while - also loops through a block of code while a specified condition is true
From the example above, you can read: Statement 1 sets a variable before the loop starts (var i =
0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3
increases a value (i++) each time the code block in the loop has been executed.
Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (i = 0). This is not
always the case, JavaScript doesn't care. Statement 1 is optional. You can initiate many values in
statement 1 (separated by comma):
Syntax
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
Example
And you can omit statement 1 (like when your values are set before the loop starts)
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Example
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable. This is not always the
case, JavaScript doesn't care. Statement 2 is also optional. If statement 2 returns true, the loop
will start over again, if it returns false, the loop will end. NB: If you omit statement 2, you must
provide a break inside the loop. Otherwise the loop will never end. This will crash your browser.
Statement 3
Often statement 3 increases the initial variable. This is not always the case, JavaScript doesn't
care, and statement 3 is optional. Statement 3 can do anything like negative increment (i--),
positive increment (i = i + 15), or anything else. Statement 3 can also be omitted (like when you
increment your values inside the loop):
Syntax
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
Example
In the following example, the code in the loop will run, over and over again, as long as a variable
(i) is less than 10:
while (i < 10) {
text += "The number is " + i;
i++;
}
Example of while loop
If you forget to increase the variable used in the condition, the loop will never end. This will
crash your browser.
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Example of do while loop
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
Example
The loop in this example uses a while loop to collect the car names from the cars array:
Syntax
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}
Example
CHAPTER FOUR
4.0 JavaScript Form Validation
Form validation occurs at the server, when the client had entered all essential data and then
pressed the Submit button. If some of the data that had been entered by the client had been in the
wrong form or there is missing fields, the server sends all the data back to the client and request
the form to be resubmitted with correct information. This consumes time and over troubling the
server. JavaScript provides a way to validate form's data on the client's computer before sending
it to the web server. Form validation generally performs two functions.
Basic Validation - First of all, the form must be checked to make sure data was entered into
each form field that required it. This would need just loop through each field in the form and
check for data.
Data Format Validation - Secondly, the data that is entered must be checked for correct form
and value. This would need to put more logic to test correctness.
Syntax
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted:
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
NB: HTML form validation does not work in Internet Explorer 9 or earlier
CHAPTER FIVE
5.0 JavaScript Error Handling
Writing programs that work when everything goes as expected is a good start. Making your
programs behave properly when encountering unexpected conditions is where it really gets
challenging. There are three types of errors in programming namely Syntax Errors, Runtime
Errors and Logical Errors.
When a syntax error occurs in JavaScript, only the code contained within the same thread as the
syntax error is affected and code in other threads gets executed assuming nothing in them
depends on the code containing the error.
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
<script type="text/javascript">
<!-try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.
Examples
Here is one example where we are trying to call a non-existing function this is causing an
exception raise. Let us see how it behaves without with try...catch:
Now let us try to catch this exception using try...catch and display a user friendly message. You
can also suppress this message, if you want to hide this error from a user.
Example
You can use finally block which will always execute unconditionally after try/catch. Here is an
example
CHAPTER SIX
6.0 Working With Cookies
A cookie is a piece of data which is sent from a website and stored locally by the users browser.
Simply are data, stored in small text files, on your computer. Cookies are needed because HTTP
is stateless. This means that HTTP itself has no way to keep track of a users previous activities.
One way to create state is by using cookies.
When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user. Therefore, cookies were invented to solve the problem "how to
remember information about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
Example
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Function explained:
Take the cookiename as parameter (cname). Create a variable (name) with the text to search for
(cname + "=").
Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).
Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length).
If the cookie is not found, return "".
The example below shows the codes that set and get a Cookie, after running the code it will just
show nothing.
Example
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
}else{
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
After running the check cookie function, it will ask to write the name of the website visitor
which will be displayed when you visit the site again.
The above codes show step by step how to create a cooking which asks you to write the name of
the user as he/she visits at the first time. This is useful for the system to know that who visited
the site at the last session.
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
After running all the code together, and then try to visit the site at the second time, the output of
out cookie will be as follows.
NB: Due to the longevity of the codes I have just selected the last two functions
CHAPTER SEVEN
7.0 Working with Dates and Time
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and
milliseconds)
7.1
Here we use a script to display dates inside a <p> element with id="demo":
The script above says: assign the value of Date() to the content (innerHTML) of the element with
id="demo".
Example of using new Date(), creates a new date object with the current date and time:
Example of using new Date(date string), creates a new date object from the specified date and
time:
Example of using new Date(number), creates a new date object as zero time plus the number.
Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time
(UTC). One day contains 86,400,000 millisecond.
Using new Date(7 numbers), creates a new date object with the specified date and time: The 7
numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:
Variants of the example above let us omit any of the last 4 parameters
The toUTCString() method converts a date to a UTC string (a date display standard).
Date objects are static, not dynamic. The computer time is ticking, but date objects, once created,
are not.
CHAPTER EIGHT
8.0 JavaScript Menus
Dropdown menus created by JavaScript are sometimes referred to as a "Jump menu" because it
"jumps" to the selected URL as soon as you make the selection. (Other drop down menus require
to click on a "go" button after you've made your selection - which is the safe way to go if you're
worried about users who don't have JavaScript enabled).
The JavaScript Menus helps to display the content of the list in the hidden data, as the code
bellow describes.
Example
The above code can be separated into two parts: the JavaScript code, and the HTML code. Here
they are separated into JavaScript code and The HTML code:
CHAPTER NINE
9.0 JavaScript, Working with Images
JavaScript also is used to display images in the website. Here it displays the image one after
another the it return to the first image as shown in figures below. You can use JavaScript to get at
and manipulate images. This may involve creating new images, setting up an array of images.
As you onmouseover, the picture become big just like the figure below.
REFERENCES
1. Marijn Haverbeke(nd) Eloquent JavaScript: A Modern Introduction to
Programming [http://eloquentjavascript.net/Eloquent_JavaScript.pdf]
4. JavaScriptTutorial
[http://www.tutorialspoint.com/javascript/javascript_tutorial.pdf]