About JavaScript
During a presentation, one should start with an “Attention grabbing” introduction that invokes emotions and generates curiosity amongst the audience. Having your own web site is very similar to a presentation; you are promoting your business or ideas and communicating with an audience.
To enable users to interact with your web site and grab their attention, web designers will recommend building Dynamic Web Pages. In these pages, the content can be updated dynamically, enabling web developers to add animation and trigger events on users’ actions.
JavaScript, formerly known as Mocha, was designed back in 1995 and was intended to work on Netscape. JavaScript is compatible with many Internet browsers and enables web developers to create functions and block of codes that run on the client machine.
Why client-side scripting?
Mainly, moving to the client browser will lessen some load from the Web Server. In addition, the processing power on the Web Server can be used to process functions that are more important.
Why not moving all code to the client side?
Scripts on the client side are plain text and easily visible. Hackers can modify the code to gain access and inject malicious code on a server (Cross-Side scripting), for more information, refer to http://www.ibm.com/developerworks/tivoli/library/s-csscript/
What goes on the client side?
Amongst others, on the client side we find:
- Validation tasks - Entries are validated before submitting the data to the Web Server.
- Formatting - Changing the HTML appearance dynamically on user actions.
- Simple calculations - Calculate simple mathematical formulas and submitting the result to the Web Server.
- Page navigation - Enables Web developers to add some logic while navigating between HTML pages.
- Animation - Enables Web Developers to add some animation that are triggered from a user action.
Remember, all code is visible, so Web Developers must be aware what code is run on the client side.
What’s in a name?
What’s the difference between JavaScript and Java? Are these the same?
To start with JavaScript is NOT Java. At first glance, some syntax may seem very similar, but the language structure is a bit different. After some research, I mapped the following table to show the main differences between both languages.
Description | JavaScript | Java |
Created | Netscape | Sun Microsystems |
Programming language model used | Object-Oriented | Object-Oriented |
Is Strongly-typed? | No | Yes |
When are errors caught? | Runtime | Compile |
Is case sensitive? | Yes | Yes |
By default, users can view code? | Yes | No |
Stand-alone | No | Yes |
Object-Based
Java is an Object Oriented language based on Classes, Objects, Interfaces and Inheritance. For more information, refer to http://download.oracle.com/javase/tutorial/java/concepts/
Whether or not JavaScript is an Object Oriented language, is debatable between developers. Reasons being that JavaScript is not stand alone (it has to be supported by HTML files) and does not follow the same style as in Java and C#.
Syntax
If you are familiar with Java, the JavaScript syntax is very similar. Every line of code should end with a semicolon ‘;’ and each block of code is defined between curly brackets ‘{ }’. JavaScript is case sensitive, so declaring a variable named ‘STRNAME’ is not ‘strname’ or ‘strName’.
Links
Similar to CSS, JavaScript can be linked to an HTML document using one of the following methods:
- In-line – JavaScript code can be defined within an HTML tag.
- Embedded – All JavaScript code and functions are included within the <Head> tag.
- External – All JavaScript code and functions are included in a separate file (.js). The HTML document is linked with the external file.
The External approach is the most recommended method to use, since this facilitates maintainability and code re-use. The image below shows how to link and HTML document to a JavaScript file.
In line 7, the <Script> tag contains information on where the JavaScript file is located and the language type used.
The Basics
JavaScript is NOT strongly typed (untyped). This means that when declaring a variable, you do not have to specify the variable type. During code execution, when assigning a value to a variable, JavaScript will automatically assign a type. All variables are declared using the var syntax; the following example shows some different declarations:
If you have a strong background in Strongly-typed languages, like C# and Java, declaring variables and following JavaScript code is a bit challenging. Assigning a variable type automatically may lead to some anomalies and to follow a complex JavaScript code may be a bit difficult. To ease maintainability, it is recommended to use meaningful names when declaring variables.
Similar to other programming languages, a variable in JavaScript has a Scope. This describes the visibility of a variable within a program. The following are the different scopes:
- Global – Variables are declared outside a function, these are visible to all functions.
- Local – Variables are declared inside a function, these are ONLY visible within the function. But if a variable is declared without using the 'var' syntax, the variable within the function becomes Global.
An ambiguity may arise when declaring two variables, one Global and one Local having the same name. To solve this ambiguity, the JavaScript interpreter gives priority to Local variables. Example, the following code will display the name ‘Omar’ since the interpreter gives priority to the Local variable.
Similar to other programming languages, a JavaScript function can have no parameters (as the image above) or a number of parameters as the code below:
Repeating a block of code several times, in JavaScript can be done using one of the conditional loops described below:
- For-Loops – A conditional loop that will run for a specified number of times.
- While-Loops – A conditional loop that will run while a condition is true.
For more information on loops, refer to http://www.w3schools.com/js/js_loop_for.asp.
Event Handlers
Event Handlers are used to execute a function when a user performs an action. For example, the following code uses the onclick() event handler to display a message when a button is clicked.
The following list describes some commonly used event handlers:
- onclick – the function is executed when the user clicks the object.
- onmouseover – the function is executed when the user hovers the mouse on the object.
- ondbclick – the function is executed when the user double clicks the object.
- onload – the function is executed when the object loads.
For more information and a full list of available event handlers, refer to http://www.w3schools.com/jsref/dom_obj_event.asp.
Document Object Modelling
The JavaScript language provides pre-defined Objects Reference; these enable developers to interact with both HTML documents and the client browser. There are three types available:
- JavaScript Objects reference – Objects within the JavaScript language, and are used to perform program logic and structure. Example: Arrays, Boolean and String.
- Browser Objects reference – Objects that enable developers to interact with the client Internet browser. Example: History, Window and Screen.
- HTML DOM Objects reference – Objects that enable developers to interact with an HTML document. Using JavaScript and these objects, developers can get or/and modify the HTML content. Example: Document, Image and Table.
For full list of all Objects Reference, refer to http://www.w3schools.com/jsref/default.asp.
Object constructor
In Java we have classes; these are templates that construct objects. To create a custom class in JavaScript, we should create a function that constructs an object as follows:
The code above, defines a user class template, having attributes firstname, lastname and age. The following code creates an instance of the class user:
Line 23 creates a user instance, while lines 24 to 26, display the new user attribute values.
Methods in JavaScript are functions attached to a class. So to add a method that increments the age by one, the code should be modified as follows:
A new function was added in lines 20 to 23, when this function is called, the age attribute is incremented by one.
Line 32 creates a user instance. In line 33 the new incrementAge method is called. Lines 24 to 26, display the new user attribute values.
Inheritance
Prototypes in JavaScript are used to implement inheritance. Let’s assume we have the following code:
The code defines three classes; person, user and administrator. Where, lines 52 to 62 define the three classes and in lines 64 to 65, user and administrator are set as a subclasses of the person class.
Code Visibility
JavaScript code is downloaded and executed in the client browser, making all source code visible to prying eyes. Hackers can modify the source code and attack/intrude into the Web Server. To prevent this to happen, Web developers use a process called Obfuscation. Using third party tools (obfuscators), the code is processed and regenerated in a way that will perform the same functions but it is difficult for a user to understand.
This article describes my experience while performing a task assigned by my tutor. The task consists of the following stages:
- Download the sample code from http://www.davidflanagan.com/javascript5/display.php?n=1-3&f=01/03.html. The example is a loan calculator.
- Since all code is embedded in one page, split the CSS, HTML and JavaScript in three files.
- Customize the design by modifying the CSS file.
- Modify the HTML to add the following in the result:
- Total number of payments
- Date when loan ends
- A check box that reduces the interest rate by 10%
- A custom feature
My Design
Adding HTML controls
When downloading the HTML from http://www.davidflanagan.com/javascript5/display.php?n=1-3&f=01/03.html noticed that the CSS and the JavaScript code were both embedded into the HTML file. So the first task was to separate the project in different files. I linked the HTML file to both the CSS and the JavaScript file as follows:
As a custom feature, I included a <DIV> tag that will dynamically update the contents when the user hovers on an object. The <DIV> tag will display a short description of the control being hovered.
To update the <DIV> contents, I added an onmouseover event handler on each control; this will execute a JavaScript function called helpfocus. The helpfocus function accepts a parameter that will contain the message to display in the <DIV> tag.
I also added a button that will print the web page when clicked. The code is as follows:
To display the Total number of payments and the Date when loan ends, I added the following HTML tags.
Then I added the discount checkbox as follws:
I modified the CSS file to customise the appearance, and the achieved output is shown below:
The JS code
The JavaScript file contains all the functions used within the Loan calculator HTML file. In this section I will describe the updates done in the JavaScript file.
To start with, I added the printdoc function, this will execute each time the Print button is clicked. The code is as follows:
To update my custom feature (the <DIV> tag); I added a function that accepts one parameter. The parameter value will be displayed in the <DIV> tag using the object.innerHTML method as shown below:
Calculation is done within the calculate function. Using the object.getElementById, the calculate function, gets the data and displays the results using object.innerHTML as shown in the code below:
I added an IF statement that checks the status of the discount checkbox. If the status is checked, the interest value will be reduced by 10%. If not, the interest rate will be the value specified by the user.
To display the last payment, I created a date object and using the date.setMonth() method I incremented the month by the number of payments as shown below:
Having some Java background and after some online research, after a couple of days I was more confident with the JavaScript syntax. I downloaded some scripts to investigate what can be done and how to do things in JavaScript. To be honest, it took me a while to understand some lengthy and complex tutorials, but overall I think that JavaScript is not difficult to learn, reason being that a lot of help is free and available online.
No comments:
Post a Comment