embedding and including write and writeln document object message box function event handler form link date window frame embedding and includinglet's first see a simple example:
html> head> title>this is a javascript example/title> script language=javascript> script> /head> body> hi, man! /body> /html>
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:
html> head>/head> body> script> .....// the code embedded in the tags. script> /body> /html>
why do we place javascript code inside comment fields ? 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:
script language=javascript1.2>
you can use another attribute src to include an external file containing javascript code:
script language=javascript src=hello.js>/script>
for example, shown below is the code of the external file hello.js:
document.write(hello world!)
the external file is simply a text file containing javascript code with the file name extension .js. note:
including an external file only functions reliably across platforms in the version 4 browsers. the code can't include tags script language...> and /script>, or you will get an error message. back to top
write and writelnin order to output text in javascript you must use write() or writeln(). here's an example:
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 and writeln is: write just outputs a text, writeln outputs the text and a line break.
back to top
document objectthe document object is one of the most important objects of javascript. shown below is a very simple javascript 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.
lastmodifiedyou can always include the last update date on your page by using the following 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 together this page created by john n. last update: and document.lastmodified.
bgcolor and fgcolorlets try playing around with bgcolor and fgcolor:
script> document.bgcolor=black document.fgcolor=#336699 /script>
back to top
message box
alertthere are three message boxes: alert, confirm, and prompt. let's look at the first one: body> script> window.alert(welcome to my site!) /script> /body>
you can put whatever you want inside the quotation marks.
confirman example for confirm box: window.confirm(are you sure you want to quit?)
promptprompt box is used to allow a user to enter something according the promotion:
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:
alert() confirm() prompt()
back to top
variables and conditionslet's see an example:
script> var x=window.confirm(are you sure you want to quit) if (x) window.alert(thank you.) else window.alert(good choice.) /script>
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.
script> var y=window.prompt(please enter your name) window.alert(y) /script>
another example:
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
functionfunctions are chunks of code.let's create a simple function:
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:
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 handlerwhat 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.
onclickonclick handlers execute something only when users click on buttons, links, etc. let's see an example:
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:
body onload=ss()> frameset onload=ss()> img src=whatever.gif onload=ss()>
onmouseover,onmouseoutthese handlers are used exclusively with links.
a href=# onmouseover=document.write('hi, nice to see you!>over here!/a> a href=# onmouseout=alert('good try!')>get out here!/a>
onunloadonunload executes javascript while someone leaves the page. for example to thank users.
body onunload=alert('thank you for visiting us. see you soon')>
handle multiple actionshow do you have an event handler call multiple functions/statements? that's simple. you just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:
form> input type=button value=click here! onclick=alert('thanks for visiting my site!');window.location='http://www.yahoo.com'> /form>
back to top
formlet's say you have a form like this:
form name=aa> input type=text size=10 value= name=bb>br> input type=button value=click hereonclick=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 how onblur works:
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>
form name=feedback> email:input type=text size=20 name=email onblur=emailchk()>br> comment: textarea name=comment rows=2 cols=20>/textarea>br> input type=submit value=submit> /form> /body>/html>
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:
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:
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>
form name=login onsubmit=return validate()> input type=text size=20 name=username> input type=text size=20 name=password> input type=submit name=submit value=submit> /form>
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().
protect a file by using login let's try an example
html>head> script language=javascript> function checklogin(x) { if ((x.id.value != sam)||(x.pass.value !=sam123)) { alert(invalid login); return false; } else location=main.htm } script>
/head>body> form> p>userid:input type=text name=id>/p> p>password:input type=password name=pass>/p> p>input type=button value=login onclick=checklogin(this.form)>/p> /form> /body>/html>
|| 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
linkin most cases, a form can be repaced by a link:
a href=javascript:window.location.reload()>click to reload!/a>
more examples:
a href=# onclick=alert('hello, world!')>click me to say hello/a>br>
a href=# onmouseover=location='main.htm'>mouse over to see main page/a>
back to top
datelet's see an example:
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().
dynamically display different pagesyou can display different pages according to the different time. here is an example:
var bantime= new date() var ss=bantime.gethours() if (ss=12) document.write() else document.write()
date objectmethods
getdate
gettime
gettimezoneoffset
getday
getmonth
getyear getseconds
getminutes
gethours
window
open a windowto open a window, simply use the method window.open():
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.
size, toolbar, menubar, scrollbars, location, statuslet's add some of attributes to the above script to control the size of the window, and show: toolbar, scrollbars etc. the syntax to add attributes is:
open(url,name,attributes)
for example:
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:
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 height toolbar
location directories status
scrollbars resizable menubar
reload to reload a window, use this method:
window.location.reload()
close windowyour can use one of the codes shown below:
form> input type=button value=close window onclick=window.close()> /form> a href=javascript:window.close()>close window/a>
loadingthe basic syntax when loading new content into a window is:
window.location=test.htm
this is the same as
a href=test.htm>try this
let's provide an example, where a confirm box will allow users to choose between going to two places:
script> !-- function ss() { var ok=confirm('click ok to go to yahoo, cancel to go to hotmail') if (ok) location=http://www.yahoo.com else location=http://www.hotmail.com } //--> /script>
remote control windowlet's say you have opened a new window from the current window. after that, you will wonder how to make a control between the two windows. to do this, we need to first give a name to the window.look at below:
aa=window.open('test.htm','','width=200,height=200')
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:
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>
openerusing opener property, we can access the main window from the newly opened window.
let's create main page:
html> head> title>/title> /head> body> form> input type=button value=open another page onclick=aa=window.open('test.htm','','width=100,height=200')> /form> /body> /html>
then create remote control page (in this example, that is test.htm):
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!
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:
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:
html> body> h2>this is page 1 /h2> a href=page3.htm onclick=parent.frame2.location='page4.htm'>click here/a> /body> /html>
notice: you should use parent.framename.location to access another frame. parent standards for the parent frame containing the frameset code.
