Wednesday, 11 January 2012

JavaScript - a basic guide

As always, W3Schools has the best tutorials about JavaScript: Simple and thanks to the "Tryit Editor", very practical. 


I am going to highlight some points that could be important.

1. General notes
  • JavaScript is usually embedded directly into HTML pages
  • JavaScript and Java are not the same.
  • JavaScript can be sensible to the events
  • JavaScript can read and write HTML elements
  • JavaScript can be used to create cookies
2. Syntax of JavaScript
2.1 General notes
  • JavaScript is case sensitive (It distinguish between Capital letters and no-capital letters)
  • The tag used by java script is
    • to start: <script type="text/javascript">
    • to finish: </script>
  • JavaScript code could be placed both in the head section and in the body section of the HTML document.
  • JavaScript allow the access to the methods and data inside of an object. This is possible by append the name of the object and the method/data with ".". For example, the follow code access to the property firstname of the object person.
person.firstname
  • According to the JavaScript standard, the default separator for different statements of the java script is EoL (End of Line), although many people believe that it is only semicolon (;). The semicolon is optional, which allow the user to have more than one statement per line.

  • To comment a code, it is the same as Java and C:
    • "//" to comment a line
    • "/*" and "*/" to comment several lines
2.2 Variables
  • The variable starts with the keyword "var", followed by the name of the variable.
  • Optionally when a variable is being declared, it can include an initial value.
  • Although the variable doesn't require the type to be declared, there are at least 3 types of variables:
    • Number: integer or float
    • String: like string in Java. They have their own methods. The symbol "+" could be used to append more than one strings
    • Boolean: true or false. It is similar to C, which allows several values for "false" and for "true":
      • False:
        • 0
        • -0
        • null
        • ""
        • false
        • undefined
        • NaN
      • True: Any other value
  • As curiosity, there are to operators for equal: "==" and "===". The first one compares only the value and the second one compares the value and the type. For example, the follow code will return true:
<html>
<body>
<script type="text/javascript">
var x = 5;
x = x + 0;
document.write(x == "5");
</script>
</body>
</html>

But the follow code will return false:
<html>
<body>
<script type="text/javascript">
var x = 5;
x = x + 0;
document.write(x === "5");
</script>
</body>
</html>

2.3 Functions
  • The functions starts with the keyword "function", followed by the name of the function and the parentheses.
  • Optionally, the functions could return a value.
  • The functions could be referred by the HTML code. For example, with the follow code, when the user press on the button, it will execute the function seeDate();
<html>
<body>
<script type="text/javascript">
function seeDate() {
document.getElementById("test").innerHTML=Date();
}
</script>
<p id = "test"></p>
<button type="button" onclick="seeDate()"> Check the date </button>
</body>
</html>

3. Referring an element
All the elements in the HTML can be referred.

  • First, the HTML itself is referred as "document".
  • The elements of HTML can have an attributes called "id".(http://www.w3schools.com/tags/att_standard_id.asp). Such attribute specified a name to the HTML element and it should be unique within the HTML element.
  • To refer an element, the method "getElementById('id')" of the class document should be used. For example:
<html>
<body>
<p id = "firstid"></p>
<script type="text/javascript">
document.getElementById("firstid");
</script>
</body>
</html>

The compiler does not read the document twice (Top-down and bottom-up). It just read from top to down. This means java script only can refers to an element which has been created previously. In other words, in order to correctly refer to an element of html in java script, the code of such element should be placed above the java script code. For example, this code won't work:

<html>
<body>
<script type="text/javascript">
document.getElementById("firstid");
</script>
<p id = "firstid"></p>
</body>
</html>

4. Reading the content of an element
After a HTML element has been referred, the variable "innerHTML" or "value" could be used to access its value. The follow example shows how to copy the content of a paragraph to another.

<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">This is a paragraphdd.</p>
<p id="copy"> Copying the text above </p>
<script type="text/javascript">
document.getElementById("copy").innerHTML = document.getElementById("demo").innerHTML;
</script>
</body>
</html> 

5. Writting elements

The object "document" has the method "write(String)" which allow the user to write any string into the html document. The compiler will replace the java script code by the string parameter of the method. For example:

<html>
<body>
<script type="text/javascript">
document.write("<p> This text has been written by java script </p>");
</script>
</body>
</html>

Be aware that if this method is executed after the page has been loaded (inside of an function executed by a button, for example), the whole web page will be reloaded. So, (See the section below)

6. Changing the value of an element
Once a HTML element has been created, it is possible change its values later, for example by clicking to a button.

In this case, the symbol equal (=) is used to assign a value:
<html>
<body>
<p id="test"></p>
<script type="text/javascript">
document.getElementById("test").innerHTML=Date();
</script>
</body>
</html>

7. Popup Boxes
JavaScript allows the code to popup three types of boxes:
  • Alert box,
  • Confirm box and
  • Prompt box. 
All them are invasive, in the sense that when they are shown, the user has to attend them as soon as possible. Because of this, my personal recommendation is utilise them as few as possible.

7.1 Alert Box
This box shows some message to the user and will stay on the page until the user press on the Accept button (the unique possible option).

The syntax is very basic:

alert("Text to show");

7.2 Confirm Box
This box asks a close question to the user and lets the user to choose between accept it or cancel it. Whenever the option that the user has chosen, it will return a Boolean. This value will be true if the user press on the "Accept" button and false if the user press on the "Cancel" button.

The syntax is also very basic:

confirm("Are you sure?");

Here is an example:

<html>
<body>
<script type="text/javascript">
var response = confirm ("Are you sure?");
if (response == true) {
document.write("Ok. I will do it");
} else {
document.write("Ok. I will cancel it");
}
</script>
</body>
</html>

7.3 The prompt box
The prompt box force the user to enter a data. It is like Alert box, but it asks an open question, which the answer won't be as simple as "Accept" or "Cancel".

The syntax is:

propmt("Question", "defaultvalue");

The difference with the alert box is the value returned:

  • If the user click on "Cancel", it will returns "null"
  • if the user click on "Accept", it will return the value in the edit box, even when it is empty.
8. Events
One of the advantages of Java Script is the possibility to capture events. They could be:

  • A mouse click
  • Mouse over a certain point of the web page
  • Select an input filed in an HTML form
  • Focusing or unfocused over a HTML element
  • When a form has been submitted
Here is a simple example which change the text to capital letters when the text field lose the focus. 

Enter some text and click on any other area.

<html>
<head>
<script type="text/javascript">
function upperCase() {
var x = document.getElementById("username").value;
document.getElementById("username").value = x.toUpperCase();
}
</script>
</head>
<body>
    Enter your name: <input type="text" id="username" onblur="upperCase()" />
</body>
</html>

Here is a list of events that could be captured:

9. Objects
Java script is an Object Oriented Programming (OOP) language, which means that it allows the users to create a class which contains its own properties and its own methods.

9.1 Creating objects
There are several ways to create an object. I am going to describe the dimpliest one.


9.1.1 Create the method
The creation of the methods could be done outside of the code of the object. The syntax is the same as the function:

function methodName([parameter1[,parametern]*]) {
//Some code
}

9.1.2 Create an empty object
Java Script allows you to create an empty object, with no properties and no methods.

The syntax is:
objectName = new Object();

9.1.3 Create variables
Once the empty object has been created, the user can append properties to it.

The syntax is:
objectName.property=value;

9.1.4 Associate the methods with the object
One way to add methods to an existence object is associate them. This requires that the methods to be created forehand.

The syntax is:
objectName.methodName = alreadyExistenceMethodName;

Notice that all the parameters of alreadyExistenceMethodName will be omitted.

One important thing is, because the methods are part of the object, they can use the keyword "this" together with the name of the properties that the object has to refer such property, even when it is "outside" of the scope of the method.

Here is a complete example of creation of an object.

<html>
<head>
</head>
<body>
<p id="rectancle" ></p>
<script type="text/javascript">
//First function of the methods
function calculateVolume() {
var volume = this.high * this.width * this.deep;
return volume;
}

//The object
rectancleObject = new Object();
rectancleObject.high = 5;
rectancleObject.width = 10;
rectancleObject.deep = 10;
rectancleObject.calculateVolume = calculateVolume;

document.getElementById("rectancle").innerHTML = rectancleObject.calculateVolume();

</script>

</body>
</html>

9.2 Object Constructor
As in Java, java script allow the user defines her own constructors, which can create objects of the same type. They syntax is almost the same as the functions. The difference is that it can has other functions inside of it.

For example:
<html>
<head>
</head>
<body>
<p id="rectancle" ></p>
<script type="text/javascript">
function rectancleObject(high, width, deep) {
this.high = high;
this.width = width;
this.deep = deep;
this.calculateVolume = function() {
var volume = this.high * this.width * this.deep;
return volume;
}
}

rectancle1 = new rectancleObject(5, 10, 10);

document.getElementById("rectancle").innerHTML = rectancle1.calculateVolume();

</script>
</body>
</html>

The objects also can be inhered through prototyping. You can find a good tutorial here:

Sources:
W3Schools tutorials - JavaScript: http://www.w3schools.com/js/

For more information:
JavaScriptKit - JavaScript and Object Oriented Programming(OOP): 
Standard ECMA-262 version 5.1, June 2011(pdf): 

2 comments:

  1. Great, thanks, I´ll be for a while with this.

    C ya

    ReplyDelete
    Replies
    1. This one of the quick dirty summary that I have done. I might check it again later and change something. Keep an eye on it.

      Delete