Showing posts with label CSS. Show all posts
Showing posts with label CSS. Show all posts

Wednesday, 2 March 2011

Introduction to JavaScript

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 NO­T 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 ON­LY 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.

Task Description

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:

Conclusion

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.

Thursday, 17 February 2011

Experience CSS

A brief overview

Not every Internet user is aware that in the early 1960s, the Internet was designed to allow military computer system to interact with each other. Back in the 60s, scientists did not predict that the Internet will evolve, as we know it today. No one knew at that time about Facebook, Google or Second life. Most probably, scientists did not predict that in the future, there will be Internet addicts, and that they can suffer from ADHD (Attention deficit hyperactivity disorder).
With all due probability, not everyone is aware that when browsing the Internet, and you click GO or Submit, you are requesting single or multiple files from a server. The sequence is more complex, in fact, there are various Protocols, and each protocol was designed to perform specific functionality. 
To request files from a server (or browse the Internet) you do not have to use Telnet as the old days. That headache is over. Today we have Internet browsers. Just key in the link and the browser will do the trick. Sounds easy, but the Internet browser engine is very complex. The engine must be able to get the user input, send requests and interpret every protocol.
Most Web site owners spend a lot of money on their web site appearance; they believe that having an attractive web site is one of the key features for a successful business. On a personal note, I think they are right.
A dynamic business, leads to a dynamic web site. Besides documentation, Web developers must keep in mind, maintainability and future expansion. To cater for these, Web developers use the Cascading Style Sheets (CSS). The CSS enables Web developers to group all the web site formatting in a single file. If the web site formatting needs to be updated or changed, only the CSS file should be modified.

Task description

This article describes my experience while performing a task assigned by my tutor. The task consists of the following stages:
  • Download a sample HTML file and its respective CSS file from www.csszengarden.com.
  • Analyze and understand the CSS content.
  • Modify the CSS file ONLY to create my own template.

Implementation

Before downloading the sample HTML and CSS, I researched a bit on the association between HTML and CSS in web development and how Web developers can implement styling. In web development, CSS styling can be implemented in three ways:

Inline

Formatting and styling is added within an HTML tag.  The following HTML code is an example of an inline style:  
Since all formatting values are specified in each tag, Web developers will find it difficult to maintain. Although this approach is still in use, it is not recommended.

Embedded or Internal

Formatting and styling is included/embedded in the HTML file and located within the <HEAD> tag.  Styles can be used by multiple tags, making maintainability much easier.
The styles are accessible ONLY within the HTML file, so to keep consistency between web pages; Web developers must copy the style parameters in each web page.

External styles

Formatting and all styles are included in a separate style file and all web pages are linked to the style file. This approach is highly recommended because it enables Web developers to apply changes to a single file. Updates are automatically applied to all web pages. Web pages can be linked by including the following code:

Cross browsers

While performing my research on how CSS can be implemented, I noticed that several Internet sources state; that CSS may behave differently across different Internet browsers. So before downloading the sample files I launched www.csszengarden.com from three of the most popular Internet browsers.
  • Microsoft Internet Explorer
  • Google Chrome
  • Mozilla Firefox
Searching the web I found lot of tips and tricks on how to detect the client browser and change the CSS accordingly. 

Analyzing samples

Browsing through the different designs in Zen Garden, I was very impressed how the CSS affects the web page appearance. To be honest, I compared some text between designs to ensure that the content is the same. The CSS is well structured and can be easily followed. Using www.w3cschools.com helped me a lot understand code blocks in both the HTML and the CSS file.

Creating my design

Hover

While I was changing some values in my CSS file, I bumped into the syntax 'hover'. This command was introduced in CSS 1 and enables Web developers to include some animation when hovering. Using the sample files, let us assume we have some text in an <H2> tag and we have the following CSS block:
 If we want to change the formatting when hovering on the text, the following block will do the trick:
The different outputs are shown in the screenshot below:

Margin and Padding

For some reasons, I always mix things up when dealing with Margins and Padding. While doing this task I took the opportunity to learn a bit more on this matter. The following image shows the relationship between the Element, Padding, Border and Margin.
Using the sample files, the following CSS block shows how the Margins and Padding can be implemented:

Colors

Colors in CSS are defined using a hexadecimal notation as shown in the following sample code :
By default the text color is blue (#009), the text color will change to green (#060) when users hover the text.
According to http://www.w3schools.com/css/css_colors.asp, the hexadecimal value is a combination of RED, GREEN and BLUE. Having values between 0 and 255 for each color, gives more than 16 million different colors. The good news is that Web developers do not need to remember all colors, many IDEs provide color palettes.

To conclude

After many CSS changes, finally I got it right. The HTML appearance is what I was expecting. The images below shows the before and after.
BEFORE
AFTER