JavaScript For Beginners
JavaScript For Beginners
Contents
Embedding and including write and writeln Document object Message box Function Event handler Form Link Date Window Frame
Usually, JavaScript code starts with the tag <script language="JavaScript"> and ends with the tag</script>. The code placed between <head> and </head>. Sometimes, people embed the code in the <body>tags:
Collapse | Copy Code
<html> <head></head> <body> <script> .....// The code embedded in the <body> tags. </script> </body> </html>
Why do we place JavaScript code inside comment fields <!-- and //-->? It's for ensuring that the Script is not displayed by old browsers that do not support JavaScript. This is optional, but considered good practice. The LANGUAGE attribute also is optional, but recommended. You may specify a particular version of JavaScript:
Collapse | Copy Code
<script language="JavaScript1.2">
You can use another attribute SRC to include an external file containing JavaScript code:
Collapse | Copy Code
<script language="JavaScript" src="hello.js"></script>
For example, shown below is the code of the external file hello.js:
Collapse | Copy Code
document.write("Hello World!")
The external file is simply a text file containing JavaScript code with the file name extension ".js". Note: 1. Including an external file only functions reliably across platforms in the version 4 browsers. 2. The code can't include tags <script language...> and </script>, or you will get an error message.
Back to top
In order to output text in JavaScript you must use write() or writeln(). Here's an example:
Collapse | Copy Code
<HTML> <HEAD> <TITLE> Welcome to my site</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JAVASCRIPT"> <!-document.write("Welcome to my site!"); // --> </SCRIPT> </BODY> </HTML>
Note: the document object write is in lowercase as JavaScript is case sensitive. The difference between write andwriteln is: write just outputs a text, writeln outputs the text and a line break.
Back to top
Document object
The document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScriptcode:
Collapse | Copy Code
document.write("Hi there.")
In this code, document is the object. write is the method of this object. Let's have a look at some of the other methods that the document object possesses.
lastModified
You can always include the last update date on your page by using the following code:
Collapse | Copy Code
<script language="JavaScript"> document.write("This page created by John N. Last update:" + document.lastModified); </script>
All you need to do here is use the lastModified property of the document. Notice that we used + to put togetherThis page created by John N. Last update: and document.lastModified.
Back to top
Message Box
alert
There are three message boxes: alert, confirm, and prompt. Let's look at the first one:
Collapse | Copy Code
<body> <script> window.alert("Welcome to my site!") </script> </body>
You can put whatever you want inside the quotation marks.
confirm
An example for confirm box:
Collapse | Copy Code
window.confirm("Are you sure you want to quit?")
prompt
Prompt box is used to allow a user to enter something according the promotion:
Collapse | Copy Code
window.prompt("please enter user name")
In all our examples above, we wrote the box methods as window.alert(). Actually, we could simply write the following instead as:
Collapse | Copy Code
alert() confirm() prompt()
Back to top
There are several concepts that we should know. First of all, var x= is a variable declaration. If you want to create a variable, you must declare the variable using the var statement. x will get the result, namely, true or false. Then we use a condition statement if else to give the script the ability to choose between two paths, depending on this result (condition for the following action). If the result is true (the user clicked "ok"), "Thank you" appears in the window box. If the result is false (the user clicked "cancel"), "Good choice" appears in the window box instead. So we can make more complex boxes using var, if and those basic methods.
Collapse | Copy Code
<script> var y=window.prompt("please enter your name") window.alert(y) </script>
Another example:
Collapse | Copy Code
<html><head>
<script> var x=confirm("Are you sure you want to quit?") if (!x) window.location="http://www.yahoo.com" </script> </head> <body> Welcome to my website!. </body></html>
If you click "cancel", it will take you to yahoo, and clicking ok will continue with the loading of the current page "Welcome to my website!". Note:if (!x)means: if click "cancel". In JavaScript, the exclamation mark ! means: "none".
Back to top
Function
Functions are chunks of code.Let's create a simple function:
Collapse | Copy Code
function test() { document.write("Hello can you see me?") }
Note that if only this were within your <script></script> tags, you will not see "Hello can you see me?" on your screen because functions are not executed by themselves until you call upon them. So we should do something:
Collapse | Copy Code
function test() { document.write("Hello can you see me?") } test()
Last linetest() calls the function, now you will see the words "Hello can you see me?".
Back to top
Event handler
What are event handlers? They can be considered as triggers that execute JavaScript when something happens, such as click or move your mouse over a link, submit a form etc.
onClick
onClick handlers execute something only when users click on buttons, links, etc. Let's
see an example:
Collapse | Copy Code
<script> function ss() { alert("Thank you!") } </script> <form> <input type="button" value="Click here" onclick="ss()"> </form>
The function ss() is invoked when the user clicks the button. Note: Event handlers are not added inside the<script> tags, but rather, inside the html tags.
onLoad
The onload event handler is used to call the execution of JavaScript after loading:
Collapse | Copy Code
<body onload="ss()"> <frameset onload="ss()"> <img src="whatever.gif" onload="ss()">
onMouseover,onMouseout
These handlers are used exclusively with links.
Collapse | Copy Code
<a href="#" onMouseOver="document.write('Hi, nice to see you!">Over Here!</a> <a href="#" onMouseOut="alert('Good try!')">Get Out Here!</a>
onUnload
onunload executes JavaScript while someone leaves the page. For example to thank
users.
Back to top
Form
Let's say you have a form like this:
Collapse | Copy Code
<form name="aa"> <input type="text" size="10" value="" name="bb"><br> <input type="button" value="Click Here"onclick="alert(document.aa.bb.value)"> </form>
Notice that we gave the names to the form and the element. So JavaScript can gain access to them.
onBlur
If you want to get information from users and want to check each element (ie: user name, password, email) individually, and alert the user to correct the wrong input before moving on, you can use onBlur. Let's see howonblur works:
Collapse | Copy Code
<html><head><script> function emailchk() { var x=document.feedback.email.value if (x.indexOf("@")==-1) { alert("It seems you entered an invalid email address.")
document.feedback.email.focus() } } </script></head><body>
If you enter an email address without the @, you'll get an alert asking you to re-enter the data. What is:x.indexOf(@)==-1? This is a method that JavaScript can search every character within a string and look for what we want. If it finds it will return the position of the char within the string. If it doesn't, it will return -1. Therefore,x.indexOf("@")==1 basically means: "if the string doesn't include @, then:
Collapse | Copy Code
alert("It seems you entered an invalid email address.") document.feedback.email.focus()
What's focus()? This is a method of the text box, which basically forces the cursor to be at the specified text box.onsubmit Unlike onblur, onsubmit handler is inserted inside the <form> tag, and not inside any one element. Lets do an example:
Collapse | Copy Code
<script> <!-function validate() { if(document.login.userName.value=="") { alert ("Please enter User Name") return false } if(document.login.password.value=="") { alert ("Please enter Password") return false } } //--> </script>
Note:
if(document.login.userName.value==""). This means "If the box named userName of
the form named login contains nothing, then...". return false. This is used to stop the form from submitting. By default, a form will return true if submitting. return validate() That means, "if submitting, then call the function validate()".
|| means "or", and ,!= indicates "not equal". So we can explain the script: "If the id does
not equal 'Sam', or the password does not equal 'Sam123', then show an alert ('Invalid Login') and stop submitting. Else, open the page 'main.htm'".
Back to top
Link
In most cases, a form can be repaced by a link:
More examples:
Collapse | Copy Code
<a href="#" onClick="alert('Hello, world!')">Click me to say Hello</a><br>
Back to top
Date
Let's see an example:
Collapse | Copy Code
<HTML><HEAD><TITLE>Show Date</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> var x= new Date(); document.write (x); </SCRIPT> </BODY></HTML>
To activate a Date Object, you can do this: var x=new Date(). Whenever you want to create an instance of the date object, use this important word: new followed by the object name().
Date object
Methods
Back to top
Window
Open a window
To open a window, simply use the method "window.open()":
Collapse | Copy Code
<form> <input type="button" value="Click here to see" onclick="window.open('test.htm')"> </form>
You can replace test.htm with any URL, for example, with http://www.yahoo.com.
For example:
Collapse | Copy Code
<form> <input type="button" value="Click here to see" onclick="window.open('page2.htm','win1','width=200,height=200,menubar')"> </form>
Another example with no attributes turned on, except the size changed:
Collapse | Copy Code
<form> <input type="button" value="Click here to see" onclick="window.open('page2.htm','win1','width=200,height=200')"> </form>
Here is the complete list of attributes you can add: width location scrollbars height directories resizable toolbar status menubar
Reload
To reload a window, use this method:
Collapse | Copy Code
window.location.reload()
Close Window
Your can use one of the codes shown below:
Collapse | Copy Code
<form> <input type="button" value="Close Window" onClick="window.close()"> </form> <a href="javascript:window.close()">Close Window</a>
Loading
The basic syntax when loading new content into a window is:
Collapse | Copy Code
window.location="test.htm"
Let's provide an example, where a confirm box will allow users to choose between going to two places:
Collapse | Copy Code
<script> <!-function ss() { var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail') if (ok) location="http://www.yahoo.com"
By giving this window a name "aa", it will give you access to anything that's inside this window from other windows. Whenever we want to access anything that's inside this newly opened window, for example, to write to this window, we would do this: aa.document.write("This is a test."). Now, let's see an example of how to change the background color of another window:
Collapse | Copy Code
<html><head><title></title></head> <body> <form> <input type="button" value="Open another page" onClick="aa=window.open('test.htm','','width=200,height=200')"> <input type="radio" name="x" onClick="aa.document.bgColor='red'"> <input type="radio" name="x" onClick="aa.document.bgColor='green'"> <input type="radio" name="x" onClick="aa.document.bgColor='yellow'"> </form> </body></html>
opener
Using "opener" property, we can access the main window from the newly opened window. Let's create Main page:
Collapse | Copy Code
<html> <head> <title></title> </head> <body> <form>
Then create Remote control page (in this example, that is test.htm):
Collapse | Copy Code
<html> <head> <title></title> <script> function remote(url){ window.opener.location=url } </script> </head> <body> <p><a href="#" onClick="remote('file1.htm')">File 1</a></p> <p><a href="#" onClick="remote('file2.htm')">File 2</a></p> </body> </html>
Try it now!
Back to top
Frame
One of the most popular uses of loading multiple frames is to load and change the content of more than one frame at once. Lets say we have a parent frame:
Collapse | Copy Code
<html> <frameset cols="150,*"> <frame src="page1.htm" name="frame1"> <frame src="page2.htm" name="frame2"> </frameset> </html>
We can add a link in the child frame "frame1" that will change the contents of not only page1, but page2 too. Shown below is the html code for it:
Notice: You should use "parent.frameName.location" to access another frame. "parent" standards for the parent frame containing the frameset code.