What Will I Learn?
- Javascript Parameters
- Javascript Variables
- Javascript Operators
- Javascript Objects
- Javascript Methods
- An Example (Code)
- An Example (Description
Requirements
- Basic HTML coding
Difficulty
- Basic
Introduction
What is JavaScript?
It is a web programming language that has a communication with HTML elements and their values. It can add or remove some effects to them and handle events which happen in the page.
JavaScript is client-side language, i.e. it is running on visitors’ computers, not on a web server. So when you run a clock script with Java, it gets the time from the visitor computer clock.
What are the differences between Java and JavaScript?
It is better to ask what are the similarities except for the name? Java is a language that can create special objects for being inserted in a web page as an 'Applet' and is more complex language than JavaScript.
JavaScript is a language inserted directly into HTML codes and no compiling or extra resources are needed to get running. But, Java needs its package to be downloaded and installed on your computer.
Introduction (JavaScript and HTML):
Before you can start JavaScript programming, you must know HTML coding. You must create your own page by one HTML editor (such as notepad) as we have said in HTML tutorial. Tables, anchors, images, forms, paragraphs, divs and etc. are HTML elements and designed by HTML language; Then it’s the time to put your java codes to make your page more intelligent; No extra editor or component is needed. You can also let visitors edit your HTML codes with JavaScript!
JavaScript codes are usually added in the <head> part of the HTML pages. To start JavaScript tag, follow this structure:
Code
<html>
<head>
<script>
</script>
</head>
<body>
</body>
</html>
Between the third and fourth tags is the place to put the JavaScript expressions. Notice that the line formation is not important (you can write all codes in one line!) and the codes are sensitive to the capital and small letters.
We will introduce the codes step by step during our lessons subhead
Your First Script
JavaScript code
Let's start a script. Scripts are a group of codes from one language that does some specific operations (a calculator is an ex.). Now we want to start a simple one that shows a message box when the page loads.
We must use a function. Functions are expressions that often get some input data and doing some operations on them and returning a value as a result or do an operation and the result is visual changes in the page instead.
A function for making a message box is in the second group. Look at its code then we’ll discuss more of it:
Code
<html>
<head>
<script>
alert('Hello World')
</script>
</head>
<body>
</body>
</html>
When you run this page (just when it loads), a message box like what you see in the following picture will be shown:
'alert' is a function that shows this box. To insert input data to the functions, you must open a parenthesis. If you have a text as an input (like a message for a message box), it must be written between single or double quotes ('text' or "text").
As we’ve said before, it is not important that we’ve inserted some spaces before 'alert' function; this is just for ourselves to show its importance!
Congratulation! You’ve successfully made your first script…
Javascript Parameters
JavaScript Parameters
HTML tags can contain some parameters. For example, you can set a background color in the '' tag by the following code:
Code
<body bgcolor='blue'>
</body>
'<Script>' tag can also have some parameters to set its properties. The first one is for choosing a language. Scripting has different languages: JavaScript, VBScript, LiveScript and etc. we must define in which language we will write our codes. If you don’t write anything here, that means you’ve chosen JavaScript. Look at the following example to see the usage of this parameter:
Code
<script language =javascript>
</script>
The second parameter introduced here is 'src'. It is useful for when you have a collection of JavaScript codes and you want to save it outside of current page because of some reasons (maybe you want to use them in different pages or they get a lot of space in the current page).
In this case, just copy your codes in a new notepad file and save it with '.js' extension; then call it in 'src' part. For example, if this file is put in the 'lib' directory with '123.js' as its name you can call it in this way:
Code
<script src ="lib/123.js">
</script>
So all the codes in this file are accessible now.
OK, let' continue to the next lesson subhead. . .
Javascript Variables
JavaScript Variables
It is very common in programming to save some data somewhere. Usually, a name is chosen for a part of computer memory to contain a specific value; so whenever the name is used, its value is called from that space, i.e. the name is a sign for its value.
We call these structure 'Variables'. For example, in the registration form, name, age, location and etc. are asked; when the visitors fill them, these new values go to their specific variables and get used within the script or sent to the destination page.
Variables values can come from different resources, the programmer himself may input them, or they may come from other web pages; it is also possible to get them from data banks, system configurations (like a date) and etc.
Let’s introduce how we can define a new variable. We’ve shown it in the following example:
Code
<script>
var Name= Value
</script>
We have three parts here. 'var' is definition word shows that we want to define a new variable and is optional (can be removed). 'Name' is your variable name and must obey some rules:
- It must starts with a letter or underscore
( _ ). You can put an underscore within it, too. - It can contain numbers but not at the first.
- It cannot contain any spaces.
- It is sensible to capital and small letters; so ‘
V1’ differs from ‘v1’. - You cannot use these characters within its name:
+-, * & ^ % # @ ! ( ) = \ / ? ~`
And finally the 'Value'. It is what we want to save in the memory space with a specified name. It has different types:
- Booleans: 'True' or 'False' values create a Boolean group of variables. They are usually used to save a logical expression result or a condition.
- Numbers:This type contains all numeric values.
- Strings: Letters, Words and Sentences are 'String' values. Even if you have a number here, it has no numeric value and it is just a character beside other ones. You must enter these values into two single or double quotes.
Let’s have some examples for understanding it better:
Code
<script>
var answere= true
var stu_Num= 20118766
var Pi= 3.1415
var userName1= 'Jacki'
var Date= "4/22/2011"
alert (answere)
</script>
As you see we use the first variable as a message box message. You can replace it with other variables and see the result.
It was an introduction to Variables.
JavaScript Operators
All of us are using mathematical basic operations very much in our lives. Adding, Subtracting, Dividing and etc. help us to act with numbers. In JavaScript like other programming languages, we have these operations with specific operators.
An operator is a few characters that do a numerical, logical or other operations for us. In this lesson we want to illustrate numerical operators. The table below is sufficient for our aim:
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Adding one value to another (directly or by variables). | a1= 3.5, a2= 4 + a1 | a2 becomes 7.5 |
| - | Subtracting one value from another | b1= 3.5, b2= 4 - a1 - .5 | b2 becomes 0 |
| * | Multiplying one value by another | c1= 2, c2= c1*c1 +1 | c2 becomes 5 |
| / | Dividing one value by another | d1= 90, d2= d1/10 + 1 | d2 becomes 10 |
| % | Remained value from dividing of it by another value | e1= 7, e2= d1 % 4 | e2 becomes 3 |
| ++ | Add one to a variable | f= 8, f++ | f becomes 9 |
| -- | Subtract one from a variable | g= 3.7, g-- | g becomes 2.7 |
| += num | Add a number to a variable current value | h= 5, h += 2 | h becomes 7 |
| -= num | Subtract a number from a variable current value | i= 5. i -= 7 | i becomes 3 |
| *= num | Multiply a variable by a number | j= 5. j *= 2 | j becomes 10 |
| /= num | Divide a variable by a number | k= 5. | k becomes 2.5 |
| %= num | A variable value becomes its remaineder from its division by a number | l= 5, l %= 2 | l becomes 1 |
The last point of this lesson is about operators orders. take a look at following statement and try to guess the result :
| Code | Result |
|---|---|
| Result= 2+3*5+18/6+(7-4)%2 alert (Result) | ? |
Parentheses are prior to other operators; the second place is for multiplication, dividing and percentaging operators ('*', '/', '%'); the one at left acts before the others from a category. The third place is for summing and subtracting ('+', '-'); and again the left operator is prior to the others.
So we can say that ((7-4= 3)) is calculated first, then ((3*5= 15)), after that ((18/6= 3)) and then ((3%2= 1)). Now it’s Summations and Subtractions that get ran ((2+15+3+1= 21)). The final result is 21.
OK, this lesson subhead is finished, too. Hope to see you in the next one!
JavaScript Objects
Everything on the page is an object. The main document, Textboxes, Anchors, Divs, and other HTML elements are object examples. Each object has its own properties like color, width, text and etc. which can be accessible by putting a dot after its name.
If you have a good HTML editor like Microsoft FrontPage, the list will be open when you put a dot in some cases. As we’ve said before, JavaScript enables you to control objects and their properties.
The first object introduced here is ‘document’ that control the whole document and you can even access to all parts of your page by this object, too. Let’s change the page title for our first example:
Code
document.title= 'My JavaScript Page'
Look at above example; we’ve chosen the desired object first (here 'document'); then we’ve inserted a dot to access its properties. Because we want to change the title, we’ve put it at the left (like variables when getting new values).
A '=' sign and new string value in the quotes are to set new title. Run the page in the browser and look at the page title at its top; you’ll see this new title name there.
Other 'document' properties are listed in the following table:
| Property | Description | Example |
|---|---|---|
| .linkColor | Unvisited links Color | document.linkColor= 'black' |
| .alinkColor | Currently Selected links Color | document.alinkColor= 'green' |
| .vlinkColor | Visited links Color | document.vlinkColor= 'red' |
| .bgColor | Page background Color | document.bgColor= "#CCFFFF" |
| .fgColor | Page foreground (texts) Color | document.fgColor ='blue' |
| .fileCreatedDate | Current page Created Date | alert(document.fileCreatedDate) |
| .lastModified | Last Modification Date of Page | alert(document.lastModified) |
| .location.host | The Address of page Host | alert(document.location.host) |
| .location.hostname | The Name of page Host | alert(document.location.hostname) |
| .location.href | The Url of the page | alert(document.location.href) |
| .location.pathname | The page Path in the host | alert(document.location.pathname) |
The four last rows of the table differ from the others. 'location' is an object too, which has taken a place inside the 'document'; so we can get access to it by a dot after 'document'. To see its properties, just follow the structure (put a dot!). We may have more than one object inside other ones, like what we have had here.
Notice that some browsers may not support some of the above properties and be careful with the CAPITAL and small letters.
Another useful object is 'window' which is used to deal with current window:
| Property | Description | Example |
|---|---|---|
| .screenLeft | Reads the distance of the page from the left side of the screen | alert(window.screenLeft) |
| .screenTop | Reads the distance of the page from the top side of the screen | alert(window.screenTop) |
| .location | Gets the page location on the host (Like document.location) | alert(window.location) |
| .screen.height | Get general screen height from screen object | alert(window.screen.height) |
| .screen.width | Get general screen width from screen object | alert(window.screen.width) |
Note that the 'window' object name can be removed from above codes and you can use them directly.
OK, Let's continue to the next lesson session…
JavaScript Methods
Methods are actions or functions that an object do, or they’re done on an object. Closing or opening a window, writing a text and etc. are some examples.
To access to a method put a dot after an object name and then write the method name (like properties); after that open a parenthesis (like 'alert' function) and insert input data (if they exist); finally, close the parenthesis.
'document' object has some useful methods listed below:
| Method | Description | Example |
|---|---|---|
| .write (sText) | Write a String Text with HTML format at the first of the page | document.write ('<br>salam') |
| .execCommand (cmdID) | Does a command like saving as or refreshing the page. | document.execCommand ('Print') document.execCommand ('SaveAs') |
And the 'window' object methods:
| Method | Description | Example |
|---|---|---|
| .alert ([message]) | 'alert' function. The message is optional. | window.alert ('Hellow') |
| .blur() | Hides the window. | window.blur () |
| .close () | Closes the window after asking a question. | window.close () |
| .confirm ([message]) | A Message Box with OK-Cancel buttons. | window.confirm ('The window is Restarted.') |
| .moveTo (x,y) | Moves the window to the specified position | window.moveTo (80,80) |
| .moveBy (x,y) | Moves the window base on the current position | window.moveBy (90,90) |
| .navigate (url) | Opens the url (Address) in the page (go | window.navigate ('http://www.javascriptfreecode.com') |
| .open ([url]) | Opens a new page (Blank if no url is specified) | window.open ('http://www.javascriptfreecode.com') |
| .prompt([message], [defstr]) | Opens A box to ask a message (optional) with an initial optional value 'defstr' | window.prompt ('Your Age?', 22) |
| .resizeTo (x,y) | Resize the window to defined size (x=width, y=height) | window.resizeTo (800,500) |
| .resizeBy (x,y) | Add x to the current width and y to the current height of the page. | window.resizeBy (-80,220) |
| .setTimeout (expression, msec) | Does an expression (JavaScript code here) cyclically after an interval (millisecond period) | window.setTimeout ("alert ('salam')" ,3000) |
| .setInterval (expression, msec) | Does an expression one time after an interval (millisecond period) | window.setInterval ("alert ('salam')" ,3000) |
At the last two rows, the expressions should be written in the quotes; we’ve written it in the double quotes because the expression itself has a string value (alert message) that must be in another quote; in fact, we’ve done it to prevent malfunctions.
Remember that the 'window object name can be removed from above codes and you can use them directly.
Note that some methods may not be supported by some browsers. They may not work properly or at all in them.
JavaScript Example 1
This Lesson is an example of what we had up to now. Take a look at it; we’ll describe what it does later:
In Notepad We Write
<html>
<head>
<script>
/* This Example has a combination of HTML and JavaScript Codes. If you aren't familiar with HTML codes, please review our Tutorial:
http://htmlfreetutorial.com*/
//Step One: Welcome Message:
var name= prompt('What is Your Name?',"")
document.write("Hello "
,name,"")
//Step Two: Window Settings:
window.resizeTo (1000,700)
window.moveTo (0,0)
setInterval("window.resizeBy (-1,-1)",500)
//Step Three: Table Settings:
</script>
</head>
<body bgcolor =#CCCCCC>
<p align="center"><u><font size="7" color="#0000FF">Welcome to My Web Page</font></u></p>
<div align="center">
<table border="1" width="40%">
<tr>
<td>This page is Modified last time:</td>
<td><script>document.write(document.fileCreatedDate)</script></td>
</tr>
<tr>
<td>Page back color:</td>
<td><script>document.write(document.bgColor)</script></td>
</tr>
<tr>
<td>Whole screen width:</td>
<td><script>document.write(window.screen.width)</script></td>
</tr>
<tr>
<td>Local location:</td>
<td><script>document.write(window.location.pathname)</script></td>
</tr>
<tr>
<td>Location on host:</td>
<td><script>document.write(document.location)</script></td>
</tr>
</table>
</div>
</body>
</html>
Copy these codes to new HTML page and run it with a browser (Mozilla Firefox is preferred). If you have a web hosting (real or local one) run it there to get a better answer.
Description: example 1
The page size should reduce cyclically. Save the page somewhere, we’ll describe it in the next lesson.
Let’s go step by step together to understand the procedure better. . .
JavaScript Example 2
Open the last example. lines with blue typeface color are HTML codes, with Black color are JavaScript codes and the Gray lines are comments.
Comments are notes written within every programming language; they don’t have a programming worth and they are only noted to recall code readers or the programmer himself something. They also can be used to add a description to help to get more familiar with the codes.
Two structures exist for commenting within JavaScript codes: first by adding double slashes ( '//' ) at the first of each comment line (one line comments), and the second one by starting a multi-line comment with '/' and ending with '/'. We’ve used both two structures above. At first, we’ve added a note in three lines and then, we described each part by a single line comment.
In 'Step One' part we have a question with 'prompt' code at first. Its result is saved in a variable ('name'). If the message box left empty, the variable value is set to 'null' that means Nothing. Then a 'Hello' message is written to the page by 'document.write ()' function.
This function can get any number of input data and will print them one after the other on the page body. The inputted data must be separated by a comma. The first and third inputs are HTML codes and the middle one is the 'name' variable (asked from a visitor by prompt message).
First we’ve opened an HTML tag in the first input part of 'write' function, then we’ve put the variable in the second part and at last, we’ve closed these tags in the third part. Note that HTML codes must come in the quotes but variables don’t need quotations.
At 'Step Two', first we’ve resized the window and moved it to the position (0,0); then, we’ve set that the window size reduces 1 unit, two times in each second, both in its height and width (negative sign set the reduction here).
At 'Step Three' we’ve created a simple table with two columns and five rows. The first column filled ordinary with HTML codes and the next column contains JavaScript tags. After each '<td>' tag of the second column, we’ve opened a JavaScript tag and put a property to be written in the specified cell.
So this column contents can vary from one visitor to another (here this happens just for the third row, i.e. the screen width may vary from one pc to another, other rows are fixed because they show page details on the server and they don’t depend on the visitors pc). Then we’ve closed both scripting tag and '<td>' tags.
This was what we’ve done in the previous lesson session example.
I really hope you like the lessons in the different session that make up this episode. Please do follow up the next episode. . .
Posted on Utopian.io - Rewarding Open Source Contributors