Learn JavaScript

Learn JavaScript

By
Prof. Dr. Muhammad Anwar-ur-Rehman Pasha
Chairman Department of Computer Science and Information Technology
University of Sargodha, Pakistan

This book will cover some of the fundamental aspects of JavaScript which are important to make your web page more attractive and functional. You will learn how to write functions, use text boxes, create conditional statements, programming loops, etc. For all of this you do not need a rich programming experience. You just need to have prior knowledge how to create your own HTML pages. In this book we have tried to use examples which help readers to learn JavaScript more easily. Your little effort will help you to achieve your target.

What is JavaScript?

The first question which you would like to ask is “What is JavaScript?”  JavaScript is a scripting language works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. It is an interpreted language. JavaScript is an easy-to-use programming language. It can be embedded in different parts of a web page, the header or the body. JavaScript allows you to embed dynamic and interactive features in your page like performing calculations, filling forms, updating the contents interactively, adding special effects, customizing graphics, etc.

What's the difference between Java and JavaScript?

One thing which confuses many new comers is the difference between Java and JavaScript. In fact, both languages are different languages. Java is a general purpose, high-level, object oriented programming language. Whereas, JavaScript is a scripting language widely used to develop web pages, desktop apps, mobile phone apps, and internet servers. Scripting languages are used to manipulate, customize, and automate the facilities of a host environment. In our case Web browser provides the host environment. It is interesting to know for programmers that the scripting code does not need a main program. The scripting code is written within the HTML code and the output page will be a combination elements defined in HTML and JavaScript code which may be fixed or computed text, images or user-interface elements.

JavaScript is much simpler and easier language for non-programmers. It is easy to learn particularly for people who do not have a programming background. JavaScript provides a mechanism to display web pages in browsers. It also allows performing server-side computation on Web-based client-server architecture. In fact, web browsers provide a host environment for JavaScript to carryout client-side computation and manipulate user-interface objects like anchors, windows, menus, dialog boxes, text areas, frames, pop-ups, history, cookies, etc. Furthermore, the host environment allows scripting code to generate some action one some events such as changing focus, uploading pages and images, submitting forms, handling mouse actions and errors, etc. It is important to note that web servers also provide a host environment for server-side computation, including objects representing requests, clients, and files, and mechanisms to lock and share data. By using browser-side and server side scripting together it is possible to develop a Web-based application which involves computation both on client and server.

What is Object Oriented Programming (OOP)?

Object-oriented programming consists of Objects, Methods and Properties. It helps to create models for real world problems. In OOP, an object is just likes a black box which has some methods which perform some actions and properties which store some information. Some of the information stored in an object can be directly accessible, whereas some information may require a method to access it. The directly accessible information is called properties of the object. Whereas, methods allow to perform  actions like writing a text to the screen, opening a window, displaying an alert box, concatenating a string, assigning a date to a variable, etc. Methods also allow changing the properties of an object. For example:

document.bgcolor="red" is a property because you are changing the existing feature of the document. alert("Hello There") is a method because displays an alert box.

Here are some commonly used methods of JavaScript:

  • Date Methods.
  • Window Methods.
  • Document Methods.
  • Form Methods.
  • History Methods.
  • Text Methods.
  • Math Methods.
  • MessageBox Methods.

Warm-up Example

Example below will illustrate how to use JavaScript methods. Write this code in an HTML file and open this file in a browser. Consequently, you will see following three items on your browser’s page, as shown in Fig 1

  • A text message.
  • A textbox.
  • A push button

 

Fig 1

Type in your name in the textbox, and press the “Create My Window” button. In response to this action the browser will display a new window, as shown in Fig 2, containing:

  • Local date and time
  • Text messages
  • A hyperlink
Fig2

The example code is very descriptive and you can easily identify the code responsible of performing these actions. Don’t worry if you feel difficulty in understanding this code. Towards the end of this section we have analyzed this code to explain the functionality of this code.

Example Code

<html>
<head>
<script type="text/javascript">
<!--
function MyWindow(message) {
//Define Date to display in local syntax
myDate = new Date()
LocalTime = myDate.toLocaleString()
 
//Define contents of page
contents=
'<body bgcolor="beige">'+
'<h2>Hello ' + message + '</h2>'+
'Welcome to my new window <br />' +
'Click the link below to close this window<br/>'+
'<A HREF="javascript:window.close()" >Click to close this window</A>'
 
//Create new Window and write contents
options = "toolbar=0,status=0,menubar=0,scrollbars=0, resizable=0,width=350,height=200"
newwindow=window.open("","myWindow", options)
newwindow.document.writeln(LocalTime)
newwindow.document.write(contents)
}
// -->
</script>
 
</head>
<body  onLoad="this.form1.text1.focus()">
 
<b>Please, enter your surname  and press the button</b>
<form name="form1">
<input type="text" name="text1" size="50" maxlength="50"> <br /><br />
<input type="button" value="Create My Window" onClick="MyWindow(form.text1.value)">
</form>
</body>
</html>

Let’s analyze JavaScript code to understand its functionalities. A JavaScript code can be appear in an HTML document both <head> and <body> parts. In this example we have embedded JavaScript code in head part. This script will be executed on the client's machine when the HTML document is loaded or when an action/event is initiated from the document. Remember, JavaScript code is written within <script type="text/javascript">… </script> tag. The value of the type attribute for <script> tag overrides the default scripting language for that element.

In this example, first of all we have declared a JavaScript function with one argument:
function MyWindow(message) {

}

MyWindow is the name o the function and “message” is its argument.

myDate = new Date()

In this statement we have created an instance of Date object and assign this instance to variable “myDate”.

LocalTime = myDate.toLocaleString()

In this statement we have converted the value of Date into local syntax.

contents= '<body bgcolor="beige">'+ '<h2>Hello ' + message + '</h2>'+'Welcome to my new window <br />' + 'Click the link below to close this window<br/>'+'<A HREF="javascript:window.close()" >Click to close this window</A>'
In this statement we have created the contents to be appeared in new Window and store it in a variable “contents”. Here we have used JavaScript function  “javascript:window.close()” within a hyperlink tag <a> …</a>. When a user clicks this hyperlink, the window.close() function will close the newly opened window.
 
options = "toolbar=0,status=0,menubar=0,scrollbars=0, resizable=0,width=350,height=200"

In this statement we have set the attribute of newly constructed window. Through these values we can control the appearance of newly constructed window.

newwindow=window.open("","myWindow", options)

In this statement we have opened a new window with defined options. Here the first argument is empty string. We can assign a URL address to argument as below:

window.open ("http://www.google.com","myWindow");

newwindow.document.writeln(LocalTime)

In this statement we have displayed the string stored in LocalTime using writeln() function.

newwindow.document.write(contents)

In this statement we have displayed the string stored in variable “contents” using write() function.

Here we have used two different functions to display/write contents on our newly constructed window.  The difference in both function is that writeln() function write on a new line.

We hope this explanation would have helped you to understand the functionalities of JavaScript.