How to use Javascript

Write your "How To" regarding anything you are comfortable with and you feel it will help the forum members.

NOTE :: All threads started here will appear only after the approval from Administrator
Post Reply
clubmaster3
Posts: 8
Joined: Sun Dec 09, 2007 1:42 pm

How to use Javascript

Post by clubmaster3 »

I think Javascript is the most popular addition to HTML.

Before i start with some examples on how to do stuff with javascript here a little definition of Javascript for those that don´t know what it is:

What is Javascript?


JavaScript is a scripting language used in many websites. A scripting language is a language, which is easy and fast to learn. So is this reference. A scripting language is interpreted in run-time. It is not compiled like other languages as C++, C#, VB.NET etc. JavaScript is a client side language and it runs on the client browser. Netscape developed it and because of its simplicity it is one of the most known scripting languages. However JavaScript can be also used on the server-side. JavaScript can be used on all most known browsers. It can be easily used to interact with HTML elements. You can validate text fields, disable buttons, validate forms, or change the background color of your page. All this is possible with JavaScript. Like each programming language, it contains variables, arrays, functions, operators, objects and much more which can be help you to create better scripts for your pages. On the server side you can use JavaScript for example to manage your database entry. JavaScript code can be inserted directly in the HTML or you can place it in a separate file with the .js extension and link the web page with the .js file.

Is JavaScript a lighter version of Java?


Many who haven’t worked before with java or scripting languages think that JavaScript is the same as Java or a lighter version of it. This is not true. Java is a different language developed by Sun Micro Systems. Java is much more complex then JavaScript. In Java you have to declare each variable with the type, in JavaScript you don’t need to do that. All variables are declared when you first time use them. Furthermore in Java you have to declare all variables, functions and classes. In JavaScript you don’t even need to think about these things. Java is compiled to byte codes on the server and the result is send to the client. JavaScript is interpreted on the client side it doesn’t require any compilation.

Usage of JavaScript


Usually web-designers design pages and coders code applications. However with JavaScript a designer has the possibility to create a client side application with very less efforts. He can easily create some kind of dynamic pages – i.e.: you can easily show a prompt box and asks the user to enter his name whenever the page loads for the first time. He can then use the entered value to create a welcome string. These procedures are called events. Events can be used and called when something occurs – like loading the page for the first time. You could also write another event which is called whenever the page is closed. JavaScript is also mostly used to validate text fields. For example in asp.net you have the possibility to validate your controls with some validator controls. These validator controls are basically nothing more then a JavaScript file. This validation can be easily written with JavaScript to verify if a text field is empty or not.

-----------------------------------------------------------------------------

Ok enough explanation for now, let´s start creating something with javascript!

How to create a running clock with javascript:

To create a clock you need:

* A mechanism to read the time
* A mechanism that repeats itself infinitly

Read the time with the object Date
JavaScript provides a standard object to cope with date and time: the object Date. To instantiate your own Date object you use the syntax:
myDateObject = new Date()
You can enter parameters to define the time but for creating a clock we don't use these parameters. The time will default to the actual time of the client computer. The object Date() has quite some methods. We do need only three of them:

* getHours(), returns the actual hour
* getMinutes(), returns the actual minute
* getSeconds(), you guessed it.., returns the actual second

Repeat infinitely


You don't just want the time. A running clock needs to update every second. To keep updating you need a recursive function. And you need to pause between each recursive call to avoid running out of resources (a stack overflow).
The standard object window provides a method setTimeout() that pauses a defineable span of time and after that time calls a function. You can put setTimeout() into a function and then call the same function. Thus creating a controllable recursion.

function do_it_often()
{......
// your syntax here
dummy = setTimeout("do_it_often()",500);
}

The second parameter of setTimeout is the timespan. It is defined in milliseconds (1/1000 of a second).
Example
With this example you can implement a running clock within your HTML-page. The actual time is shown within a textfield of a form. The JavaScript source has been made as short as possible; you can include it in your webpage and it costs you only a few bytes.
The example uses a parameter to define a 0-24 hr clock or a 0-12 am/pm clock.

Javascript Source:

Code: Select all

<SCRIPT  type="text/javascript" >
<!--  Hiding for non JS Browsers
var timetype = 12;
function timing(){
   var t = new Date();
   var h = t.getHours();
   var m = t.getMinutes();
   var s = t.getSeconds();
   mstxt = ((m < 10) ? ":0" : ":") +
      m + ((s < 10) ? ":0" : ":") + s;
   ****.timeform.time.value=
      (timetype==24)?(((h<10)?"0":"")+
      h+mstxt):(((h>12)?h-12:h)+mstxt+
      ((h>=12)?" PM":" AM"));
      clock = setTimeout("timing()",1000);
}

function start_timing(input_timetype)
{  timetype = input_timetype;
   timing();
}
-->
</SCRIPT>

HTML Source:

Code: Select all

<BODY onLoad="start_timing(12)">
and

Code: Select all

<FORM name="timeform">
    <INPUT type="text" name="time" size="12">
</FORM>
Put the JavaScript source somewhere between the tags <HEAD> en </HEAD>

The HTML source can be placed anywhere in the body of your webpage. Don't forget to adjust the body-tag. If you want to use a 24-hour clock put the number 24 between the parentheses.

Additional Information:

The function start_timing() is used to set the global variable timetype. The function timing() repeatedly reads the time and writes it to the field time in the form timeform. It formats the time before writing it. Essentially it checks if a zero should be inserted. And it adapts the output for am/pm or for a 24 hour presentation.

-----------------------------------------------------------------------------

Rounding

JavaScript provides a standard object Math that has a rounding method. But this method only rounds to whole numbers.
Rounding to a fixed decimal length
In the first version of this script an error would occur if you rounded numbers like 8.495 to 2 decimals. This gave the incorrect result 8.49 instead of 8.50.
The following routine copes with this situation, thanks to David Marcionek who was so kind to notify me of this error. David also found a routine that coped with this error and he made some corrections to that routine.
JavaScript source
The function fdp (fixed decimal point) can be used in your pages if you put the following source in the header.
The function checks for decimal lengths. It only accepts a decimal length of 10 or less.
If the length is negative it is changed into zero.

Code: Select all

<SCRIPT  type="text/javascript" >
<!-- hide for non JS browsers
function fdp(n,d){
	var **** = n.indexOf('.')
	var l = n.length
	var zstr = '0000000000000000000000'
	var theInt = ''
	var theFrac = ''
	var theNo = ''
	rfac = ''
	rfacx = 0
	nx = 0
	var xt = parseInt(d) + 1
	var rstr = '' + zstr.substring(1,xt)
	var rfac = '.' + rstr + '5'
	var rfacx = parseFloat(rfac)
	if (**** == -1 ) 	{    // No fraction
		theFrac = zstr
		theInt = "" + n
	}
	else if (**** == 0) {
		theInt = '0'
		nx = 0 + parseFloat(n) + parseFloat(rfacx)
		n = nx + zstr
		theFrac = '' + n.substring(1, n.length)
	}
	else {
		theInt = n.substring(0,****)
		nx = parseFloat(n) + rfacx
		n = '' + nx + zstr
		theFrac = '' + n.substring(****+1,**** + 1 + parseInt(d))
		var astr = 'd = ' + d
	}
	theFrac = theFrac.substring(0,parseInt(d))
	var ii = 0
	theNo = theInt + '.' + theFrac
	return theNo
}
-->
</SCRIPT>
HTML source
With the following source you can test the function fdp().

Code: Select all

<FORM name="testForm">
Enter a number  <INPUT type="text" name="a">

Enter decimal places <INPUT type="text" name="b">

Result <INPUT type="text" name="c">

<INPUT type="button" value="Calculate"
   ****="testForm.c.value =
   fdp(testForm.a.value,  testForm.b.value)">
</FORM>
-----------------------------------------------------------------------------
Updating a page

After updating a page, it's good practice to show date the the page was last modified. You can type in the date but you can also show it automatically.
The JavaScript object **** has an attribute lastModified.
You can use it like this:
****.write(****,lastModified)
If things go wrong
Mostly, this will give you the results you want.
But in some **** the date can be completely wrong. What happens?
The information about the date is provided in a HTTP package. However, this is not obliged.

If the information is missing or wrongly interpreted, the value of ****.lastModified defaults to the Unix epoch: January 1, 1970 0h0m0s, sometimes also shown as December 31, 1969, 23h 59m 59s.
You don't want a modification date in 1970. There weren't any web pages around at that time!
How to solve it
The solution is to check the results. If the result is somewhere around 1970, it's obviously wrong.
A good method to test is the method parse() from the object Date.
Date.parse() returns the number of milliseconds after the Unix epoch date.
If the returned date is correct, the value returned by Date.parse() should be larger than 0.

Here's a piece of Javascript that does the job:

Code: Select all

<SCRIPT  type="text/javascript" >
if (Date.parse(****.lastModified) > 0) {
   ****.write("Page last modified: ",****.lastModified) }
else  {
   ****.write("Modification date could not be determined") }
</SCRIPT>

Ok that´s it for now:D
I hope it will be usefull for some of yours!


SHAdmin
Posts: 2089
Joined: Sat Dec 18, 2004 11:28 am
Contact:

Post by SHAdmin »

Hi,
35 points have been credited into your account for the "How To".
Post Reply