Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Java and Web Design

Unit 6

Unit 6

Using JavaScript

Structure: 6.1 Introduction Objectives 6.2 Overview of JavaScript Origin of JavaScript Purpose of JavaScript 6.3 Using JavaScript in a Web Page 6.4 Event Handlers List of event handlers supported by JavaScript Using event handlers Use of event handlers using functions 6.5 Benefits and Drawbacks of JavaScript 6.6 Summary 6.7 Glossary 6.8 Terminal Questions 6.9 Answers 6.10 Caselet

6.1 Introduction
By now you must be familiar with the concept of web servers. You have studied about Apache web server and its different features. You have also studied the various methods to secure the Apache web server. This unit helps you to learn JavaScript, which is a programming language used to create interactive and dynamic web page. You will thus learn to create web pages that are more interesting than the HTML pages which are static. In this unit we will first begin by analysing the meaning and features of JavaScript. Then we will discuss about the origin of JavaScript. We will also study the reasons for using JavaScript to create web pages. Then, we will learn to embed a simple JavaScript code in our HTML document. We will also learn about event handlers that help to make our web page interactive, and then we will discuss few programs that use event handlers. We shall also discuss about the benefits and drawbacks of using JavaScript in our web pages.
Sikkim Manipal University Page No. 102

Java and Web Design

Unit 6

Learning Objectives: After studying this unit, you should be able to: explain the purpose of JavaScript. use simple JavaScript code in a web page. describe the purpose of an event handler. explain why JavaScript can be difficult to manage.

6.2 Overview of JavaScript


As any other programming language JavaScript is also a programming language. To be more precise JavaScript is a user interface scripting language developed by Netscape Communication Corporation. We can use this language to add interactivity to our web page thus enhancing the look and feel of the user interface. For example, we can perform calculations, include special effects, and display alert messages by embedding the JavaScript code within a HTML (HyperText Markup Language) code. The JavaScript code that we embed within an HTML code helps in recognising and responding to user events such as form input, mouse clicks, and page navigation. We can use JavaScript to write scripts that can be identified by the server and the client computer. Even though JavaScript has Java in its name it is distinguishably different from the Java programming language. JavaScript is an open language that can be used by anyone without having to purchase a license to use it. Let us now see some of the features of JavaScript: It is an object based language. We can identify objects as containers that are used to store more than one value. JavaScript supports built-in and user-defined objects. It is supported by all platforms such as Windows, DOS, and Macintosh. We can execute the JavaScript program on Internet Explorer as well as other browsers. It supports events and thus provides user interaction such as, mouse click, mouse over, key pressed, and so on. Thus, the browser identifies the event present in the JavaScript program and executes the program accordingly.

Sikkim Manipal University

Page No. 103

Java and Web Design

Unit 6

6.2.1 Origin of JavaScript As we are now aware of some key features of JavaScript, let now see how this JavaScript originated. We know that HTML helps in the creation of static web pages, when the World Wide Web (WWW) was created it contained only static web pages. Hence you could see the page exactly as it was setup to show, without any scope for interaction between the you and the web page. Do you not feel it could be very boring to work on such static pages? However, in order to implement this interactivity into the web pages there was the need for a programming language to give instructions to the web page in order to respond to your actions. Realising the need for interactivity in web pages Netscape Communication Corporation came up with a programming language, known as LiveScript. This language was integrated into the browser as the browser will identify the commands without any need for compiling the code and without any need of a plug-in to be able to run it. LiveScript was later renamed as JavaScript. The syntax of JavaScript code is similar to that of Pascal and C programming language. In 1996 this programming language was handed over to the European Computer Manufacturers Association (ECMA) which is an international standards body. It took over the responsibility of future development of this language. It was then again renamed officially as ECMAScript or ECMA-262. However, most of us still are referring to it as JavaScript. 6.2.2 Purpose of JavaScript After you have learnt the meaning and origin of JavaScript, let us now study the various purpose of using JavaScript. Some of the purposes of using JavaScript are as follows: It is widely used as it facilitates interactivity to your web page by creating interfaces that are highly responsive. This improves the user experience and provides dynamic functionality to your web page. It reduces the server load because once the web page is downloaded the server becomes free to serve other visitors. This is possible as JavaScript software runs on the browser present in the users computer and does not require reloading of the page in order to facilitate user interactions.

Sikkim Manipal University

Page No. 104

Java and Web Design

Unit 6

It helps in validating forms. Validation refers to checking for mistakes in forms before we submit them. For example, whenever you are entering data into an online form you might have observed you get an alert message box asking you to enter details into a particular field that you might have forgotten to enter. This is done using JavaScript. It helps to constantly update information that change periodically without any user interaction. For example, crickets match score. It facilitates you to create search box that provides you suggested results when you type the first few letters of your search keyword. This is known as 'autocomplete'. For example, if you type ai it could bring up various suggestions such as, 'air', 'airtel', 'aircell', 'air india', and so on. It helps you to animate the elements on a web page. For example, you can make part of your web page that contains images to move around on the page. It can be used to create rollover images and scripted slideshows which add dynamic effect to your web page.

Self Assessment Questions 1. JavaScript is a user interface ___________ language developed by Netscape Communication Corporation. 2. What does ECMA stand for? 3. JavaScript can be used to create _________ images and scripted slideshows which adds dynamic effect to your web page. Activity 1: Consider a scenario where you are working for ABC Software Ltd. as a web developer. Your organisation uses only HTML and CSS in the creation of web pages. You being aware of JavaScript and its purposes would like to implement this language in the creation of web pages. How would you go about convincing your organisation and team members in doing the same? Hint: Explain the purposes of using JavaScript.

6.3 Using JavaScript in a Web Page


You now know the meaning and purposes of using JavaScript in your web page. Let us now study how we can use JavaScript in our web pages. We
Sikkim Manipal University Page No. 105

Java and Web Design

Unit 6

will first look into, what you need to create a JavaScript. We need a text editor, for example, notepad, and a web browser, for example, Internet Explorer. The requirements are the same as we had for creating a web page using HTML page. We can use any text editor and web browser for executing the JavaScript. However, for our learning purpose we will make use of note pad and Internet Explorer. We will now look into the syntax used to write a JavaScript code. The following is the basic syntax you use to write a JavaScript code: <script type="text/javascript"> <!-JavaScript Code --> </script> Let us now look into the explanation of the above syntax: <script> - This is the opening tag that will tell the browser to expect a JavaScript code instead of HTML. <!- - - - > - This is the comment tag similar to that we use in HTML. The purpose of using these inside JavaScript code is to inform the browser to ignore the code between them in case it does not support JavaScript. Adding the code in between comment tag prevents the code from being displayed on the webpage. </script> - This is the closing tag that tells the browser that it is the end of the JavaScript program. Now let us consider an example to understand it better. In this example we will see the method to write text to a web page using JavaScript.
<script type="text/javascript"> <!-document.write("Hello I am learning JavaScript"); --> </script>

You can see that we have used the document.write method in the above code and applied the syntax. The code that does the work of writing text to a web page is: document.write("Hello I am learning JavaScript");
Sikkim Manipal University Page No. 106

Java and Web Design

Unit 6

Here, document is a window object that refers to the current document being displayed in a window. write is a document object that writes the line Hello I am learning JavaScript to your web page. If you try to run only the above code, it will not serve any purpose. Thus, we have to now embed this code snippet into the HTML program. Let us now see how to do this. We can do this my placing the JavaScript code within the <head> tag of the HTML program. The following program depicts the inclusion of JavaScript code in HTML program: <html> <head> <title>JavaScript Program</title> <script type="text/javascript"> <!-document.write("Hello... I am learning JavaScript."); --> </script> </head> </html> To execute the above code you follow the same procedure as you do for an HTML program. That is, type the program in a text editor, in our case it is the notepad. Then, save it as an .html file. let us save our program as display.html and save it on the desktop (you can save it anywhere on your hard disk. For the matter of convenience we have decided to save it on desktop). You can then double click the HTML file saved on your desktop, or open the browser, that is, Internet Explorer and then from the file menu open the html file.

Sikkim Manipal University

Page No. 107

Java and Web Design

Unit 6

Figure 6.1 depicts the output as displayed on your browser.

Figure 6.1: Output of the Program to Display a Line

Self Assessment Questions 4. The __________ is a window object that refers to the current document being displayed in a window. 5. We should place the <script> tag within the <body> tag of the HTML program. (True / False)? 6. Explain <script> tag. Activity 2: Write a JavaScript code to display the line JavaScript is a simple programming language. Hint: Use the following code within the <script > tag: document.write("JavaScript is a simple programming language");

6.4 Event Handlers


You have now got an understanding of writing a simple JavaScript program for your web page. Let us now move ahead and learn about event handlers and the way you can use them in your web page.
Sikkim Manipal University Page No. 108

Java and Web Design

Unit 6

Before we learn the meaning of event handlers, let us first have a look at what you mean by an event. We can refer to an event as an action that you perform on a web page such as, a mouse click that is used to initiate an action. When an event is initiated the execution of a specific block of code gets triggered. Some other examples of events are, moving a mouse over a text or an image or submitting a form. So, what do you mean by event handlers? Event handlers refer to commands that are executed to handle an event that is triggered by the user action. Event handlers serve various purposes. Some of them are as follows: It can be used to respond to events or actions. It can be used to respond to events that are initiated by the users, such as mouse click, mouse over, and so on. It can also be used for loading images and pages that do not have much user involvement and takes place automatically when the web page is loaded in the browser window. It brings life to your web page by helping to add inter-activeness. 6.4.1 List of event handlers supported by JavaScript Now that you have learnt the meaning of events and event handlers, let us now study some of the event handlers that are frequently used in a JavaScript program. Table 6.1 provides us with a list of event handlers with their description.
Table 6.1: Event Handlers Event Handler onClick Description Triggered when you click the mouse button. Used For: Button, Link, Reset, Submit, Checkbox, Document Image, Link Image, Link Document, Link, Button Document, Link, Button Page No. 109

onMouseOut onMouseOver onMouseDown onMouseUp

Triggered when the browser loads a web page. Triggered when you move the mouse pointer over the area of focus. Triggered when you press a mouse button. Triggered when you release the mouse button.

Sikkim Manipal University

Java and Web Design

Unit 6

onResize onSelect onFocus

Triggered when you resize the browser window or frame. Triggered when you select a form field. Triggered when the area or object receives focus. Triggered when the area or object loses focus. Triggered when you press a key.

Window TextArea, Text Form, Frame, Button, Window, Text, TextArea Form, Frame, Button, Window, Text, TextArea Image, Link, TextArea, Document Image, Link, TextArea, Document Image, Link, TextArea, Document Form Window, Image Window Image

onBlur

onKeyDown

onKeyUp

Triggered when you release a key.

onKeyPress

Triggered when you press or hold down a key. Triggered when you click the forms submit button. Triggered when the browser loads a window. Triggered when you exit a document. Triggered when loading of the image is cancelled.

onSubmit onLoad onUnload onAbort

6.4.2 Using event handlers You now familiar event handlers that refer to commands used to trigger an event, and also learnt about the widely used JavaScript event handlers. Now, let us look into a program that uses a few of the event handlers that we discussed in the above table. As we did earlier we will embed these codes within the HTML tags. This would give you an understanding as to how web developers use JavaScript in their HTML program to add interactivity to their web pages. The following HTML code has JavaScript embedded in it that uses onMouseOver, onMouseOut, and onClick event handlers.

Sikkim Manipal University

Page No. 110

Java and Web Design

Unit 6

<html> <head> <title>My First Web Page</title> </head> <body> <form> <a HREF="http://www.smude.edu.in/" onMouseOver = "document.bgColor = '#FF0000' " onMouseOut = "document.bgColor = '#00FF00' " onClick = "alert ('Thank You... You will be now redirected to Sikkim Manipal Univerity Web Site') "> <b> Move your mouse over me! </b> </a> </form> <hr/> </body> </html> When you run the above code in your web browser you can find a link reading Move your mouse over me! try moving your mouse over the link. You will observe that the background colour changes to red. Now move your mouse away off the link. You will see that background colour again changes to green. Now try clicking on the link, you will get a message box which says Thank You... You will be now re-directed to Sikkim Manipal University Web Site. Did you not feel it was interesting? So, let us now see how all this happened. As you have already worked on HTML tags, let us only look into the use of event handlers in the above code. When you moved your mouse on the link the background colour changed to red. This was because of the use of onMouseOver event handler. The background colour changed to green because of the use of onMouseOut event handler. The colour changes happen with the following lines of code: onMouseOver = "document.bgColor = '#FF0000' " onMouseOut = "document.bgColor = '#00FF00' " Here, onMouseOver and onMouseOut act as variables which store the events that have to occur when the mouse is over or off the link. The event
Sikkim Manipal University Page No. 111

Java and Web Design

Unit 6

here says that the background colour of the document has to change to the colour code that is given within single quotes. The colour code is given in hexadecimal format prefixed by a hash mark (#). For example, as in our example, #FF0000 represents the colour red and #00FF00 represents the colour green. In the colour code, the first two digits symbolise the red level, the next two digits symbolise the green level, and the last two digits symbolise the blue level. Thus, the code FF0000 will be pure red, 00FF00 will be pure green, and 0000FF will be pure blue. You can use a combination of these to get different colours of your choice. We use these hexadecimal notations for the combination of Red, Green, and Blue colours, widely known as RGB. RGB is used to represent the colours that are used on a computer display. Here, document is a window object that refers to the current document being displayed in a window and bgColor refers to the document object that specifies the background colour. We learnt, how to change the background colour, but how did we get that message box which displayed, Thank You... You will be now re-directed to Sikkim Manipal University Web Site. For this we have used the onClick event handler. Following is the code that did this job: onClick = "alert ('Thank You... You will be now redirected to Sikkim Manipal University Web Site')" As you rightly guessed the onClick event handler is assigned the task of displaying a message box. Here, the alert() method is used to display an alert dialog box, which displays the message specified within parenthesis and single quotes. 6.4.3 Use of event handlers using functions You have now learnt the method to implement event handlers in your program. The one you learnt was a simple method to use event handlers. The other method to implement event handlers in your program is by the use of functions. Web developers use a lot of functions in their web pages. Before we learn to write a program to implement event handlers using functions, let us first learn what a function means? Function refers to a block of code that is reusable and that gets executed when they are called. You must define a function within the <script> tag in
Sikkim Manipal University Page No. 112

Java and Web Design

Unit 6

the <head> section of the HTML program. It is easy to identify a function in a program by its format. It is depicted as a piece of descriptive text along with open and close parenthesis. We can also find text within the parenthesis known as argument. This argument is passed to the function to give necessary information to the function to process the information. The syntax to define a function is as follows: <script> <!-function functionName(argument1, argument2) { JavaScript Code 1 JavaScript Code 2 } --> </script> As you can see the function is defined within the <script> tag and is declared with the use of the function keyword, which is followed by a function name that you define. It consists of parenthesis which contains the arguments that has to be passed to the function. The JavaScript code within the flower braces will contain the action that will be take place when a particular condition is satisfied by the function. Any function will get executed only when it is called in the program. We should also note that the keyword function should always be in lowercase for JavaScript to recognise it as a function. This is because JavaScript is case sensitive when compared to HTML which is not case sensitive. Let us now analyse a program that uses functions to implement event handlers. This program displays an input box and a button named display message on your web page. When you enter your name into the input box and click on the button, an alert message is displayed.

Sikkim Manipal University

Page No. 113

Java and Web Design

Unit 6

<html> <head> <title> JavaScript Program </title> <script type="text/javascript"> <!-function displayMessage(enterName) { alert("Hello " + enterName + ", you learnt to implement event handlers using functions") } --> </script> <body> <!--Call the function:--> <form> Enter your name: <input type="input" name="yourName" /> <input type="button" onclick="displayMessage(form.yourName.value)" value="Display Message" /> </form> </body> </html> Let us now understand the working of the above code. As you can see we have used a function within the <script> tag. The function keyword will inform the browser that a function is defined. Then, the function is named as displayMessage which is user defined. Then we pass an argument to the function ("enterName"), which refers to the name of the argument. There is a pair of curly braces which contains the code that the function has to perform when it is called. Here, we have specified a user defined function "alert()" that will pop up a message when an event is triggered. Now that we have declared the function to display an alert message, we have to now call the function in our program. For this, we have created an input field and a submit button within the <form> tag. Then we name the the input field ("yourName"). Later, an onClick event handler is created for the button. The event handler is called when you click the button.
Sikkim Manipal University Page No. 114

Java and Web Design

Unit 6

When you click the button the event handler calls the function displayMessage. The value entered in the input box is read using the "form.yourName.value". Figure 6.2 depicts the output as displayed on your browser.

Figure 6.2: Output of the Program to Display an Alert Message

Self Assessment Questions 7. The __________ refers to as an action that is performed by the user to initiate an action. 8. When an event is initiated the execution of a specific block of code gets triggered. (True / False)? 9. What do you mean by event handlers? 10. The __________ event handler is triggered when the mouse pointer moves over the area of focus. 11. The __________ event handler is triggered when loading of the image is cancelled. 12. What is a function?
Sikkim Manipal University Page No. 115

Java and Web Design

Unit 6

Activity 3: Consider a scenario where you are working as a web developer in SCN software Pvt. Ltd. You are using JavaScript to add dynamic effects to your web page that you are working on. Your project manager asks you to add a JavaScript code to display a message "Welcome to AZ mart" when the page loads on the users browser. Which event handler would you use to display this message? Hint: Refer sub section 6.4.1 List of event handlers supported by JavaScript.

6.5 Benefits and Drawbacks of JavaScript


You now know that JavaScript is a programming language used to create interactive web pages that can be run from any browser rather than from the server. You also learnt how we can add interactivity to our web page by executing a simple program which contained the event handlers. From all our discussions above we now know that JavaScript has various benefits. Let us now discuss some of the benefits of using JavaScript. They are as follows: JavaScript can be used to lessen the time taken for data validation as the validations happen on your computer. We need not send the data to the server for the purpose of validating the data. This also reduces the heavy internet traffic. JavaScript supports enhanced user interactivity such as, navigational tools and pop up boxes. We can load new images on the web page without having to reload the page. We can reuse the JavaScript code by embedding it in multiple programs. Therefore, you can save time by using a particular block of code that was used before to perform the same functionality. We can use JavaScript to download plug-ins, if the your browser does not have a plug-in installed. The JavaScript can detect the plug-ins automatically, that are added to a browser. Java Script is very quick as it is runs on the client-side, and therefore any code can run immediately without having to wait for the server to respond.
Sikkim Manipal University Page No. 116

Java and Web Design

Unit 6

We can easily implement a JavaScript code by adding the code in your HTML document and intimate the browser that it is JavaScript. We can use JavaScript program to send commands for different types of browsers. Thus, you can use JavaScript to write programs, which could be loaded on different browsers. JavaScript is considered to be very versatile as it works well with many other languages other than HTML. Regardless of the file extension, it can be inserted into any web page. We can also use it in the development of various applications as well. We can even use it within scripts written in other languages such as PHP and Perl.

Even though JavaScript has many benefits as mentioned above, it has a few drawbacks. The drawbacks of JavaScript are as follows: As you know JavaScript programs run on the user's computer. This feature can also be considered as a weakness as it can be used for malicious purposes, such as, to run a virus as soon as the web page gets loaded. Thus, posing a threat for security. JavaScript codes are read by different browsers differently. As a result of which you need to test your code on different browsers in order to ensure that it works the same way in all web browsers. When you embed JavaScript in your web page it reduces its search engine friendliness. This is because the search engine finds it difficult to search for keywords if the JavaScript code is not stored separately. The use of JavaScript limits the accessibility of website as some of the mobile devices or old browsers do not recognise JavaScript. Also, some of us prefer turning off the JavaScript support for security reasons. The use of JavaScript many a times disturbs the users. For example, you might have come across many websites which will try to pop up windows which display advertisements without your permission. Self Assessment Questions 13. JavaScript supports enhanced user ____________ such as, navigational tools and pop up boxes. 14. Using JavaScript we can load new images on the web page without having to reload the page. (True / False)? 15. When you embed JavaScript in your web page it reduces its _____________________.
Sikkim Manipal University Page No. 117

Java and Web Design

Unit 6

6.6 Summary
In this unit we studied about a programming language known as JavaScript that is used to develop dynamic and interactive web pages that is either not possible or difficult with HTML alone. We discussed about the origin of JavaScript and found that it was developed by Netscape Communication Corporation and was first named as LiveScript. It was later renamed as JavaScript and is now handed over to European Computer Manufacturers Association (ECMA) which is an international standards body that took over the responsibility of future development of this language. We even studied about the various purposes of JavaScript such as, adding interactivity, reducing server load, validating forms, adding animations, and so on. We also learnt to embed JavaScript code in our HTML document after understanding the syntax of JavaScript. We even learnt about event handlers which are commands to handle the events that are triggered by the user of the web page. We learnt about the various event handlers available such as, onClick, onMouseOver, onMouseOut, onSubmit, onFocus, onBlur, and so on. We also discussed few programs that used event handlers with and without using functions. Later, we also discussed about the various benefits and drawbacks of using JavaScript.

6.7 Glossary
Term Case sensitive Parenthesis Plug-in Rollover images Syntax Trigger User interface Description It is program's ability to differentiate between uppercase and lowercase alphabets. Open and close curved brackets. It is an add-on to a program that is used to add additional functionalities. It is an effect created by the web page in order to ease the navigation for the user of the web page. It is a set of grammar rules to ascertain the correctness of a programming language. An action that initiates a function or command. It is the part of computer program that is interactive and which sends messages and receives instructions from the user of the system.

Sikkim Manipal University

Page No. 118

Java and Web Design

Unit 6

6.8 Terminal Questions


1. 2. 3. 4. 5. Explain the various purposes of using JavaScript? List any six event handlers and describe the same. Write a JavaScript code to write text to a web page. Explain the benefits and drawbacks of JavaScript. Briefly explain the origin of JavaScript.

6.9 Answers
Self 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. Assessment Questions: Scripting European Computer Manufacturers Association Rollover document False <script> tag is the opening tag that will tell the browser to expect a JavaScript code instead of HTML. Event True Event handlers refer to commands that are executed to handle an event that is triggered by the user. onMouseOver onAbort Functions refer to block of codes that are reusable and that gets executed when they are called. Interactivity True Search engine friendliness

Terminal Questions: 1. Refer sub section 6.2.2 Purpose of JavaScript. 2. Refer sub section 6.4.1 List of event handlers supported by JavaScript. 3. Refer section 6.3 Using JavaScript in a web page. 4. Refer section 6.5 Benefits and drawbacks of JavaScript. 5. Refer sub section 6.2.1 Origin of JavaScript.

Sikkim Manipal University

Page No. 119

Java and Web Design

Unit 6

6.10 Caselet
SDFG Software Private Limited is a software company which is into web development from the past ten years. It works with reputed companies as its clients. Its client list spans more than hundred and fifty in number. It has successfully developed various varieties of web pages for its clients and was earning good amount of profits up till the previous year. This year they have noticed a considerable amount of decrease in profits when compared to the previous years in spite of the quality work they have undertaken in the development of websites for their clients. They have been also offering the websites that they develop to the clients at a reasonable rate. When they conducted a survey to find out the reason for the sudden decrease in their revenue they found that their clients were moving towards GHNM Software Private Limited which was offering to develop web pages at the same rate as SDFG Software Private Limited. On further investigation it was discovered that GHNM Software Private Limited was developing websites that were interactive and dynamic, when compared to SDFG Software Private Limited that was developing only static web pages using HTML and CSS. Questions: 1. What do you think is special with interactive and dynamic web pages, when web pages developed using HTML and CSS will also be colourful and serves the purpose of giving the needed information to the end user? Hint: Interactive and dynamic web pages serve various purposes other than giving information to the end user. Refer sub section 6.2.2 Purpose of JavaScript) 2. What do you think GHNM Software Private Limited used to generate interactive and dynamic web pages? Hint: JavaScript.

Sikkim Manipal University

Page No. 120

Java and Web Design

Unit 6

References Ramesh Bangia, Khanna book publishing Pvt. Ltd (2007), Learning Web Designing. Danny Goodman with Michael Morrison, Wiley Publishing, Inc., sixth edition, JavaScript Bible. http://javascript.about.com/od/reference/a/history.htm http://www.pageresource.com/jscript/jbasics.htm

Sikkim Manipal University

Page No. 121

You might also like