javascript language: form validation, cookies, date format and condition statement

42
1 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13 MOSHI CO-OPERATIVE UNIVERSITY (MoCU) Faculty: Faculty of Business Information System. (FBIS) 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: Individual Assignment Report. Date: 04th June 2015.

Upload: matokeo-msavange

Post on 15-Sep-2015

31 views

Category:

Documents


4 download

DESCRIPTION

A 2nd student at Moshi Co-operative University, taking Bachelor of Science in Business information and Communication Technology (Bsc.BICT)

TRANSCRIPT

  • 1 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    MOSHI CO-OPERATIVE UNIVERSITY

    (MoCU)

    Faculty: Faculty of Business Information System.

    (FBIS)

    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: Individual Assignment Report.

    Date: 04th June 2015.

  • 2 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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

    2.1The if Statement ..................................................................................................................... 5

    2.2 The else Statement ................................................................................................................. 5

    2.3 The else. if Statement ......................................................................................................... 6

    2.4 Switch Statement ................................................................................................................... 7

    CHAPTER THREE ...................................................................................................................................... 8

    3.0 JavaScript Loops ..................................................................................................................................... 8

    3.1 Different Kinds of Loops ...................................................................................................... 9

    3.1.1 The For Loop .................................................................................................................... 10

    Statement 1 ................................................................................................................................ 11

    Statement 2 ................................................................................................................................ 12

    Statement 3 ................................................................................................................................ 13

    3.1.2 The For/In Loop ............................................................................................................... 14

    3.1.3 The While Loop ................................................................................................................ 15

    3.1.4 The Do/While Loop .......................................................................................................... 16

    3.1.5 Comparing For and While ................................................................................................ 17

    CHAPTER FOUR ....................................................................................................................................... 18

    4.0 JavaScript Form Validation .................................................................................................................. 18

    4.1 Basic Form Validation ......................................................................................................... 19

    4.2 Data Format Validation ....................................................................................................... 20

    CHAPTER FIVE ........................................................................................................................................ 20

    5.0 JavaScript Error Handling ..................................................................................................................... 20

    5.1 Syntax errors ........................................................................................................................ 21

    5.2 Runtime errors ..................................................................................................................... 21

    5.3 Logical errors ...................................................................................................................... 21

  • 3 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    5.4 Situations that encountered by Programmers ...................................................................... 22

    5.5 The throw Statement ........................................................................................................... 24

    CHAPTER SIX ........................................................................................................................................... 25

    6.0 Working With Cookies ......................................................................................................................... 25

    6.1 How It Works ...................................................................................................................... 25

    6.2 Create a Cookie with JavaScript ......................................................................................... 26

    6.3 Read a Cookie with JavaScript ............................................................................................ 27

    6.4 Change a Cookie with JavaScript ........................................................................................ 27

    6.5 Delete a Cookie with JavaScript ......................................................................................... 27

    6.6 JavaScript Cookie Example ................................................................................................. 27

    6.6.1 A Function to Set a Cookie .............................................................................................. 28

    6.6.2 A Function to Get a Cookie .............................................................................................. 28

    6.6.3 A Function to Check a Cookie ......................................................................................... 29

    6.6.4 All code of cookie Together Now .................................................................................... 31

    CHAPTER SEVEN .................................................................................................................................... 32

    7.0 Working with Dates and Time .............................................................................................................. 32

    7.1 JavaScript Date Formats ...................................................................................................... 32

    7.1.1 Displaying Dates .............................................................................................................. 33

    7.1.2 Creating Date Objects ...................................................................................................... 33

    CHAPTER EIGHT ..................................................................................................................................... 38

    8.0 JavaScript Menus .......................................................................................................................... 38

    8.1 The JavaScript ............................................................................................................................... 38

    8.2 The HTML .................................................................................................................................... 39

    CHAPTER NINE ........................................................................................................................................ 39

    9.0 JavaScript, Working with Images ......................................................................................................... 39

    9.1 Displaying Multiple images ................................................................................................ 39

    9.2 onmouseover and onmouseout ............................................................................................ 40

    REFERENCES ........................................................................................................................................... 42

  • 4 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    To explain the Following Concept as used in JavaScript Language

    CHAPTER ONE

    1.0 JavaScript Introduction

    JavaScript is a scripting language designed primarily for adding interactivity to Web pages and

    creating Web applications. The language was first implemented by Netscape Communications

    Corp. in Netscape Navigator 2 beta, 1995.

    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 if to specify a block of code to be executed, if a specified condition is true

    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

    Use switch to specify many alternative blocks of code to be executed

  • 5 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    2.1 The if Statement We use if statement to specify a block of JavaScript code to be executed if a condition is true.

    The if statement is the fundamental control statement that allows JavaScript to make decisions

    and execute statements conditionally.

    Syntax of the if Statement

    if (condition) {

    block of code to be executed if the condition is true

    }

    Under the if statement, JavaScript expression is evaluated. If the resulting value is true, given

    statement(s) are executed. If expression is false then no statement would be executed. Most of

    the time it will use comparison operators while making decisions.

    Example if condition statement

    Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

    2.2 The else Statement

    We use else statement to specify a block of code to be executed if the condition is false. If the

    block of code to be executed is false, then we use else statement to print the results.

  • 6 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Syntax for else Statement

    if (condition) {

    block of code to be executed if the condition is true

    } else {

    block of code to be executed if the condition is false

    }

    Example of the else condition statement

    2.3 The else. if Statement

    We use else if statement to specify a new condition if the first condition is false.

    Syntax for else if Statement

    if (condition1) {

    block of code to be executed if condition1 is true

    } else if (condition2) {

    block of code to be executed if the condition1 is false and condition2 is true

    } else {

    block of code to be executed if the condition1 is false and condition2 is false

    }

  • 7 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Example of else.if statement

    If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00,

    create a "Good day" greeting, otherwise a "Good evening":

    2.4 Switch Statement

    Use the switch statement to select one of many blocks of code to be executed.

    Syntax for Switch Statement

    switch(expression) {

    case n:

    code block

    break;

    case n:

    code block

    break;

    default:

    default code block

    }

    This is how it works:

    The switch expression is evaluated once.

    The value of the expression is compared with the values of each case.

    If there is a match, the associated block of code is executed.

  • 8 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Example of switch condition statement

    The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1,

    Tuesday=2 ..)

    Use the weekday number to calculate weekday name:

    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] + "";

    text += cars[1] + "";

    text += cars[2] + "";

    text += cars[3] + "";

    text += cars[4] + "";

    text += cars[5] + "";

  • 9 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Loops let you run a block of code a certain number of times.

    You can only write:

    for (i = 0; i < cars.length; i++) {

    text += cars[i] + "";

    }

    Example

    3.1 Different Kinds of Loops

    JavaScript supports different kinds of loops:

    for - loops through a block of code a number of times

    for/in - loops through the properties of an object

    while - loops through a block of code while a specified condition is true

    do/while - also loops through a block of code while a specified condition is true

  • 10 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    3.1.1 The For Loop The for loop is often the tool you will use when you want to create a loop. Loops through a block

    of code a number of times. The for loop has the following syntax:

    for (statement 1; statement 2; statement 3) {

    code block to be executed

    }

    Statement 1 is executed before the loop (the code block) starts.

    Statement 2 defines the condition for running the loop (the code block).

    Statement 3 is executed each time after the loop (the code block) has been executed.

    Example of for loop

    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.

  • 11 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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] + "";

    }

    Example

    And you can omit statement 1 (like when your values are set before the loop starts)

  • 12 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    var i = 2;

    var len = cars.length;

    var text = "";

    for (; i < len; i++) {

    text += cars[i] + "";

    }

    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.

  • 13 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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] + "";

    i++;

    }

    Example

  • 14 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    3.1.2 The For/In Loop

    The JavaScript for/in statement loops through the properties of an object:

    Syntax

    var person = {fname:"John", lname:"Doe", age:25};

    var text = "";

    var x;

    for (x in person) {

    text += person[x];

    }

    Example for/in loop

  • 15 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    3.1.3 The While Loop

    The while loop loops through a block of code as long as a specified condition is true.

    Syntax

    while (condition) {

    code block to be executed

    }

    Example of while loop

    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.

  • 16 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    3.1.4 The Do/While Loop

    The do/while loop is a variant of the while loop. This loop will execute the code block once,

    before checking if the condition is true, then it will repeat the loop as long as the condition is

    true.

    Syntax

    do {

    code block to be executed

    }

    while (condition);

    Example

    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!

  • 17 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    3.1.5 Comparing For and While

    The while loop is much the same as a for loop, with statement 1 and statement 3 omitted.

    The loop in this example uses a for loop to collect the car names from the cars array:

    Example

    var cars = ["BMW", "Volvo", "Saab", "Ford"];

    var i = 0;

    var text = "";

    for (;cars[i];) {

    text += cars[i] + "";

    i++;

    }

    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] + "";

    i++;

    }

  • 18 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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.

  • 19 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    4.1 Basic Form Validation

    Here we show how to do a basic form validation. In the above form we are calling validate()

    function to validate data when onsubmit event is occurring. Following is the implementation of

    this validate() function:

    HTML form validation can be done by a JavaScript. If a form field (fname) is empty, this

    function alerts a message, and returns false, to prevent the form from being submitted.

    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:

    HTML Form Example

    Name:

  • 20 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    NB: HTML form validation does not work in Internet Explorer 9 or earlier

    4.2 Data Format Validation

    Unlike basic from validation, data format validation asks to comply with the format then the data

    will be send otherwise the server will return to the client asking to refill the correct format data.

    Good example is how to validate an entered email address which means email address must

    contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email

    address, and the last dot must at least be one character after the @ sign.

    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.

  • 21 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    5.1 Syntax errors

    Syntax errors, also called parsing errors, occur at compile time for traditional programming

    languages and at interpret time for JavaScript. For example, the following line causes a syntax

    error because it is missing a closing parenthesis:

    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.

    5.2 Runtime errors

    Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).

    For example, the following line causes a run time error because here syntax is correct but at run

    time it is trying to call a non-existed method:

    Exceptions also affect the thread in which they occur, allowing other JavaScript threads to

    continue normal execution.

    5.3 Logical errors

    Logic errors can be the most difficult type of errors to track down. These errors are not the result

    of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives

    your script and you do not get the result you expected. You can not catch those errors, because it

    depends on your business requirement what type of logic you want to put in your program.

  • 22 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    5.4 Situations that encountered by Programmers

    The problematic situations that a program can encounter fall into two categories: Programmer

    mistakes and genuine problems. If someone forgets to pass a required argument to a function,

    that is an example of the first kind of problem. On the other hand, if a program asks the user to

    enter a name and it gets back an empty string, that is something the programmer can not prevent.

    In general, one deals with programmer errors by finding and fixing them, and with genuine

    errors by having the code check for them and perform some suitable action to remedy them (for

    example, asking for the name again), or at least fail in a well-defined and clean way.

    JavaScript implements the try...catch...finally construct as well as the throw operator to handle

    exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch

    JavaScript syntax errors. The try statement lets you test a block of code for errors, catch

    statement lets you handle the error while throw statement lets you create custom errors, and the

    finally statement lets you execute code, after try and catch, regardless of the result.

    Here is the try...catch...finally block syntax:

    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.

  • 23 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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

  • 24 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    You can use finally block which will always execute unconditionally after try/catch. Here is an

    example

    5.5 The throw Statement

    You can use throw statement to raise your built-in exceptions or your customized exceptions.

    Later these exceptions can be captured and you can take an appropriate action.

    Following is the example showing usage of throw statement.

  • 25 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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.

    Cookies are saved in name-value pairs like:

    Username=Matokeo Msavange

    When a browser request a web page from a server, cookies belonging to the page is added to the

    request. This way the server gets the necessary data to "remember" information about users. In

    many situations, using cookies is the most efficient method of remembering and tracking

    preferences, purchases, commissions, and other information required for better visitor experience

    or site statistics.

    6.1 How It Works

    The server sends some data to the visitor's browser in the form of a cookie. The browser may

    accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,

    when the visitor arrives at another page on your site, the browser sends the same cookie to the

    server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

    Cookies are a plain text data record of 5 variable-length fields:

    Expires: The date the cookie will expire. If this is blank, the cookie will expire when the

    visitor quits the browser.

  • 26 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Domain : The domain name of your site.

    Path : The path to the directory or web page that set the cookie. This may be blank if you

    want to retrieve the cookie from any directory or page.

    Secure : If this field contains the word "secure" then the cookie may only be retrieved

    with a secure server. If this field is blank, no such restriction exists.

    Name=Value : Cookies are set and retrieved in the form of key and value pairs.

    Cookies were originally designed for CGI programming and cookies' data is automatically

    transmitted between the web browser and web server, so CGI scripts on the server can read and

    write cookie values that are stored on the client.

    JavaScript can also manipulate cookies using the cookie property of the Document object.

    JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current

    web page.

    6.2 Create a Cookie with JavaScript

    JavaScript can create, read, and delete cookies with the document.cookie property.

    With JavaScript, a cookie can be created like this:

    document.cookie="username=Matokeo Msavange";

    You can also add an expiry date (in UTC time). By default, the cookie is deleted when the

    browser is closed:

    document.cookie="username=Matokeo Msavange; expires=Thu, 18 Dec 2013 12:00:00 UTC";

    With a path parameter, you can tell the browser what path the cookie belongs to. By default, the

    cookie belongs to the current page.

  • 27 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    6.3 Read a Cookie with JavaScript

    With JavaScript, cookies can be read like this:

    var x = document.cookie;

    document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value;

    cookie3=value;

    6.4 Change a Cookie with JavaScript

    With JavaScript, you can change a cookie the same way as you create it:

    document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

    The old cookie is overwritten.

    6.5 Delete a Cookie with JavaScript

    Deleting a cookie is very simple. Just set the expires parameter to a passed date:

    document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

    Note that you don't have to specify a cookie value when you delete a cookie.

    6.6 JavaScript Cookie Example

    In the example to follow, we will create a cookie that stores the name of a visitor. The first time a

    visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a

    cookie. The next time the visitor arrives at the same page, he will get a welcome message. For

    the example we will create 3 JavaScript functions:

    1. A function to set a cookie value

    2. A function to get a cookie value

    3. A function to check a cookie value

  • 28 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    6.6.1 A Function to Set a Cookie

    First, we create a function that stores the name of the visitor in a cookie variable:

    Example of how to set a cookie

    function setCookie(cname, cvalue, exdays) {

    var d = new Date();

    d.setTime(d.getTime() + (exdays*24*60*60*1000));

    var expires = "expires="+d.toUTCString();

    document.cookie = cname + "=" + cvalue + "; " + expires;

    }

    Example explained

    The parameters of the function above are the name of the cookie (cname), the value of the cookie

    (cvalue), and the number of days until the cookie should expire (exdays). The function sets a

    cookie by adding together the cookiename, the cookie value, and the expires string.

    6.6.2 A Function to Get a Cookie

    Then, we create a function that returns the value of a specified cookie:

    Example function getCookie(cname) {

    var name = cname + "=";

    var ca = document.cookie.split(';');

    for(var i=0; i

  • 29 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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.

    6.6.3 A Function to Check a Cookie Last, we create the function that checks if a cookie is set. If the cookie is set it will display a

    greeting or ask to write the name for father reference of the created cookie.

    If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores

    the username cookie for 365 days, by calling the setCookie function:

  • 30 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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.

  • 31 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    6.6.4 All code of cookie Together Now Below is the syntax for setting, getting, and checking of cookies

    function setCookie(cname,cvalue,exdays) {

    var d = new Date();

    d.setTime(d.getTime() + (exdays*24*60*60*1000));

    var expires = "expires=" + d.toGMTString();

    document.cookie = cname+"="+cvalue+"; "+expires;

    }

    function getCookie(cname) {

    var name = cname + "=";

    var ca = document.cookie.split(';');

    for(var i=0; i

  • 32 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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 JavaScript Date Formats

    A JavaScript date can be written as a string:

    Sat May 30 2015 14:32:05 GMT+0300Thu May 28 2015 22:34:23 GMT+0300

    or as a number:

    14329855255881432841663261

    Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

  • 33 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    7.1.1 Displaying Dates

    In this tutorial we use a script to display dates inside a element with id="demo":

    Here we use a script to display dates inside a element with id="demo":

    The script above says: assign the value of Date() to the content (innerHTML) of the element with

    id="demo".

    7.1.2 Creating Date Objects

    The Date object lets us work with dates.

    A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

    Date objects are created with the new Date() constructor.

    There are 4 ways of initiating a date:

    "highELE">new Date()

    "highELE">new Date(milliseconds)

    "highELE">new Date(dateString)

    "highELE">new Date(year, month, day, hours, minutes, seconds, milliseconds)

  • 34 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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:

  • 35 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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:

  • 36 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    Variants of the example above let us omit any of the last 4 parameters

    JavaScript counts months from 0 to 11. January is 0 and December is 11.

    When you display a date object in HTML, it is automatically converted to a string, with the

    toString() method.

  • 37 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    The toUTCString() method converts a date to a UTC string (a date display standard).

    The toDateString() method converts a date to a more readable format:

    Date objects are static, not dynamic. The computer time is ticking, but date objects, once created,

    are not.

  • 38 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    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:

    8.1 The JavaScript

    This JavaScript code consists of a function we've called jumpto. This function uses

    document.location.href to load the URL provided by the jump menu (which is stored in the x

    parameter). This accepts a parameter called x, which is the value we pass in when we call the

    function in our HTML. In the following code I've changed the form name to form2 to avoid any

    conflict with the above example (which uses form1). You can call your form anything you like.

  • 39 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    8.2 The HTML

    The HTML part is what displays the actual dropdown menu, which in this case is an HTML

    element. You can change the values here to your own URLs. Of course, you're more

    than welcome to leave them as they are. All codes and output are explained in the above figure.

    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.

    9.1 Displaying Multiple images

    Below is an example of JavaScript codes and output which shift or display the images one after

    another in the list.

    First image in the list

  • 40 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    The image changed to the second image as the figure below.

    Second image in the list

    From the second image it will go up to the 9 image then, it will start again to display image 0,

    then the process is continuously and repeated.

    9.2 onmouseover and onmouseout

    Again, JavaScript can be used to enlarge the picture when moving the Caser over and out the

    image. In the image below the picture seen to be small before placing the caser over.

  • 41 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    As you onmouseover, the picture become big just like the figure below.

  • 42 MATOKEO MSAVANGE, REG No. MoCU/BICT/084/13

    REFERENCES

    1. Marijn Haverbeke(nd) Eloquent JavaScript: A Modern Introduction to

    Programming [http://eloquentjavascript.net/Eloquent_JavaScript.pdf]

    2. Rebecca Murphey ( No date) JavaScript Basics

    Based on jQuery Fundamentals [http://github.com/rmurphey/jqfundamentals]

    and [https://autotelicum.github.io/Smooth-CoffeeScript/literate/js-intro.html]

    3. JavaScript Introduction: [https://www.ohio.edu/technology/training/upload/Java-

    Script-Reference-Guide.pdf]

    4. JavaScriptTutorial

    [http://www.tutorialspoint.com/javascript/javascript_tutorial.pdf]