SlideShare a Scribd company logo
Andy's JavaScript Tutorial
    PDF Electronic Version Reproduced By: Khurram Hussain Zuberi on May 09, 2000
NOTE: The original Andy's tutorial site is located at http://andyjava.simplenet.com/ where more updated version might be found.



   FAQs on JavaScript
"What is JavaScript? Is it advanced HTML? Java? Some form of Active X?" Actually, none of the
above. JavaScript is JavaScript, and that's that. One of the most common preconceptions
about JavaScript is that it's somewhat related to Java (since they have very similar names).
Ironically, JavaScript and Java, besides the fact that they are all programming languages, are
completely different. I won't go into detail what Java is, but I will say this: it's something I
definitely won't be taking on in the near future (hint: Java is very hard to learn).
Ok, let's shift our focus back to JavaScript. "What can it do? Why should I learn it? How long
will it take me to learn it? Do I have to learn it?" Wow, that's a lot of questions. First, the
short answer, then the long:
Short answer: Cool stuff. Just because. 1-2 weeks. No.
Now, the long: JavaScript can greatly enhance the "coolness" and interactivity of your web
page. Great stuff you see on the net such as image flips, drop down menu boxes, live clocks
etc are all written in JavaScript. If you want your web pages to look more than just a bunch
of stale and boring paper documents converted into digital form, you'll want to learn this
neat programming language. It's very easy to get a handle on; I spent around two weeks- on
and off- learning JavaScript, and that was it!

   Writing your first script
Are you ready to write your first script? No, it's not too soon. A bare-bone script consists of
only two lines: The <script></script> tag:
<script>
</script>
The actualJavaScript codes will fall inside this tag. Ok, are you ready to do something
interesting with JavaScript? I thought so.

  Dynamically changing the document's background
color
Ok, let's begin by seeing how to change the background color of the document using
JavaScript. Take a look:
<script>
document.bgColor="blue"
</script>
You can change blue to any color name, or the color's hex representation (ie: #000000).
This is a very simple illustration of JavaScript at work; changing the background color isn't
exactly something good-old HTML can't do easily all by itself. However, this is just the
beginning of our JavaScript journey...have some patience!

   Status bar messages
Using JavaScript, you can display messages in the status bar of your browser below. This is
accomplished by setting a string value to the "window.status" property. For example:
<script>
window.status="Welcome to my homepage"
</script>
By doing the above, the message "Welcome to my homepage" is shown in the status bar. One
trick you may have seen on the web is a status bar message that is initiated only when the
user moves her mouse over a link:
Yahoo
Here's the code used:
<a href="http://www.yahoo.com" onMouseover="window.status='Click here for
Yahoo!';return true" onMouseout="window.status=''">Yahoo</a>
I captured the mouse's "position" by using the onMouseover and onMouseout event handlers of
JavaScript. Event handlers are added directly inside certain HTML tags such as the <a> tag,
and allows you to run code that react to a certain event (such as when the mouse moves over
a link). In this case, the code displays "Click here for Yahoo!" in the status bar when the
surfer moves her mouse over the link "Yahoo", and resets the status bar when the mouse
moves out. Pretty cool, uh?

   On-the-fly text
Text inside the document is usually static- if you reload this document 5 times, there's no
reason to believe that the document's text will be any different each time...or is there? One
of the coolest things about JavaScript is that it allows you to generate text on the fly. You
could, for example, have the document greet you "Good morning" in the morning, and "Good
night" at night. The basic way to write out text in JavaScript is by using the document.write()
command, as follows:
<script>
document.write('Some text')
</script>
Whatever you put inside the parentheses, JavaScript displays it on the page. Taking this basic
idea one step further, I'll create a script that writes out the last modified date of this page.
<script>
var modifieddate=document.lastModified
document.write(modifieddate)
</script>
The above is a perfect example of "on-the-fly" text. The text reflects the last modified date
of your page, and is updated automatically whenever you edit the page and save it!

   JavaScript dialog boxes
So, what the heck are JavaScript dialog boxes? Well, they are interesting little "pop-up" boxes
that can be used to display a message, ask for confirmation, user input etc. They're very easy
to create, not to mention cool!
Three types of dialog boxes exist in JavaScript- alert, confirm, and prompt. I'll show you an
example of each:
Alert:
<script>
alert("Welcome, my friend!")
</script>
Confirm:
<script>
var answer=confirm("Jump to CNN?")
if (answer)
window.location="http://cnn.com"
</script>
Prompt:
<script>
var answer=prompt("Please enter your name")
alert("Hello "+answer)
</script>

All of the boxes allow you to customize the message simply by entering in a different text
inside the function's parentheses. Go ahead, try it now on your web page!

   Image submit button
JavaScript is not only practical, it's cosmetical as well! If you work with HTML forms (and who
doesn't?), then you should agree that form buttons are probably one of the most ugly things
ever to exist inside a browser. They're dull, ugly, and desperately need a make-over! Well,
with the help of JavaScript, it's actually possible to use a custom image in place of form
buttons to perform the important task of sending the form's content to you. Here's how:
1) Give your form a name:
<form name="andy">
"
</form>
2) Replace the usual submit button (<input>) with the below:
<form name="andy">
"
<a href="javascript:document.andy.submit()"><img src="myimage.gif"></a>
</form>
That's it. For the submit button, noticed that I used an image link with an unusual url:
javascript:document.andy.submit(). This line of code tells JavaScript to submit the form
named andy when the link is clicked on. Here's an actual example of a form with an image
submit button:

Name:

Email:



   Displaying a random message/ image
I get a lot of emails asking me stuff like: "How do I display a random quote on my page?", or
"Is it possible to have a random image show up each time the surfer reloads the page?" The
answer? No problemo! JavaScript can be used to easily accomplish just that.
The below's a "random" quote example, where a quote out of three is randomly displayed
each time this page is loaded (Reload this web page to see another quote):
Here's the source code used:
<script>
var whichquote=Math.round(Math.random())*3
if (whichquote<=1)
document.write('"You can take away my life, but you can never take away my freedom!"')
else if (whichquote<=2)
document.write('"I'll be back"')
else if (whichquote<=3)
document.write('"You can count on it"')
</script>

The key here is the code:
var whichquote=Math.round(Math.random())*3

I'll explain this code by breaking it down: Math.random() is a JavaScript method, and always
generates a real number between 0 and 1. Math.round() rounds that number to an integer. By
multiplying that number by 3, I always get a random number that's between 0 and 3. Why 3?
Because I have three quotes I want to randomly display, so I need three random "slots". If you
have 5 quotes, just multiple the code by 5 instead.
Now, quotes are great, but what if you want to display a random image? Simple. Just change
the text to the <img> tag:
<script>
var whichquote=Math.round(Math.random())*3
if (whichquote<=1)
document.write('<img src="first.gif">')
else if (whichquote<=2)
document.write('<img src="second.gif">')
else if (whichquote<=3)
document.write('<img src="third.gif">')
</script>

Don't you just love JavaScript?

   Advanced JavaScript applications
Ok, I'll dedicate this final tutorial to showing you some more advanced JavaScript
applications, along with their complete source code, so you can simply cut and paste 'em to
instantly "pump up" your site!

   JavaScript live clock
This is a cool script that displays a "live" form clock on your web page:
 5:50:32 PM

Source code:
<form name="time">
<input type="text" name="time2" size=15>
</form>
<script>
function liveclock(){
var curdate=new Date()
var hours=curdate.getHours()
var minutes=curdate.getMinutes()
var seconds=curdate.getSeconds()
var suffix="AM"
if (hours>=12){
suffix="PM"
if (hours>=13)
hours-=12
}
if (minutes<10)
minutes="0"+minutes
if (seconds<10)
seconds="0"+seconds
var thetime=hours+":"+minutes+":"+seconds+" "+suffix
document.time.time2.value=thetime
setTimeout("liveclock()",1000)
}
liveclock()
</script>


   Image Flip
An image flip is a cool JavaScript effect that makes an image change to another when the
mouse moves over it. Not very practical, but defintely cool:


The above button consists of two images - one before the mouse is over it, and one after.
Here's the source code:
Source code:
<a href="index.htm" onMouseover="if (document.images) document.images.menu.src='after.gif'"
onMouseout="if (document.images) document.images.menu.src='before.gif'"><img src="before.gif"
name="menu" border=0></a>

Try pasting the above code onto your webpage, and change 'before.gif' and 'after.gif' to
reflect your own images. Notice how I gave the image a name ('menu') using the name
attribute. This is neccessary, and if you want to have multiple image flips on one page, you'll
need to give each image flip a unique name.

   Drop down menu box
I'ms sure most of you have seen a drop down menu box before. They are <select> lists that go
to the selected url when clicked on...a great space saver!

Geocities        GO

<form name="c1">
<p><select name="c2" size="1">
<option selected value="http://www.geocities.com">Geocities</option>
<option value="http://www.happypuppy.com">Happypuppy</option>
<option value="http://www.gamespot.com">Gamespot</option>
</select>
<input type="button" value="Go"
onClick="location=document.c1.c2.options
[document.c1.c2.selectedIndex].value"></p>
</form>

You can cram in as many links as you wish into the box simply by adding more options to the
selection list.
Recommended JavaScript sites:
    Website Abstraction- A superb JavaScript technology center featuring free scripts and
tutorials on many aspects of JavaScript. I credit most of my JavaScript knowledge to this
site.

    Dynamic Drive- Quite an amazing JavaScript site with advanced JavaScripts/DHTML
scripts you can simply cut and paste onto your site to intantly add magic to your site. I must
have used at least a dozen of them on my personal site already...

More Related Content

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascripttutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascripttutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 
Winter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20JavascriptWinter%200405%20-%20Advanced%20Javascript
Winter%200405%20-%20Advanced%20Javascript
 
eng2u3less38
eng2u3less38eng2u3less38
eng2u3less38
 
eng2u3less38
eng2u3less38eng2u3less38
eng2u3less38
 

Recently uploaded

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 

Recently uploaded (20)

GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 

andyjs

  • 1. Andy's JavaScript Tutorial PDF Electronic Version Reproduced By: Khurram Hussain Zuberi on May 09, 2000 NOTE: The original Andy's tutorial site is located at http://andyjava.simplenet.com/ where more updated version might be found. FAQs on JavaScript "What is JavaScript? Is it advanced HTML? Java? Some form of Active X?" Actually, none of the above. JavaScript is JavaScript, and that's that. One of the most common preconceptions about JavaScript is that it's somewhat related to Java (since they have very similar names). Ironically, JavaScript and Java, besides the fact that they are all programming languages, are completely different. I won't go into detail what Java is, but I will say this: it's something I definitely won't be taking on in the near future (hint: Java is very hard to learn). Ok, let's shift our focus back to JavaScript. "What can it do? Why should I learn it? How long will it take me to learn it? Do I have to learn it?" Wow, that's a lot of questions. First, the short answer, then the long: Short answer: Cool stuff. Just because. 1-2 weeks. No. Now, the long: JavaScript can greatly enhance the "coolness" and interactivity of your web page. Great stuff you see on the net such as image flips, drop down menu boxes, live clocks etc are all written in JavaScript. If you want your web pages to look more than just a bunch of stale and boring paper documents converted into digital form, you'll want to learn this neat programming language. It's very easy to get a handle on; I spent around two weeks- on and off- learning JavaScript, and that was it! Writing your first script Are you ready to write your first script? No, it's not too soon. A bare-bone script consists of only two lines: The <script></script> tag: <script> </script> The actualJavaScript codes will fall inside this tag. Ok, are you ready to do something interesting with JavaScript? I thought so. Dynamically changing the document's background color Ok, let's begin by seeing how to change the background color of the document using JavaScript. Take a look:
  • 2. <script> document.bgColor="blue" </script> You can change blue to any color name, or the color's hex representation (ie: #000000). This is a very simple illustration of JavaScript at work; changing the background color isn't exactly something good-old HTML can't do easily all by itself. However, this is just the beginning of our JavaScript journey...have some patience! Status bar messages Using JavaScript, you can display messages in the status bar of your browser below. This is accomplished by setting a string value to the "window.status" property. For example: <script> window.status="Welcome to my homepage" </script> By doing the above, the message "Welcome to my homepage" is shown in the status bar. One trick you may have seen on the web is a status bar message that is initiated only when the user moves her mouse over a link: Yahoo Here's the code used: <a href="http://www.yahoo.com" onMouseover="window.status='Click here for Yahoo!';return true" onMouseout="window.status=''">Yahoo</a> I captured the mouse's "position" by using the onMouseover and onMouseout event handlers of JavaScript. Event handlers are added directly inside certain HTML tags such as the <a> tag, and allows you to run code that react to a certain event (such as when the mouse moves over a link). In this case, the code displays "Click here for Yahoo!" in the status bar when the surfer moves her mouse over the link "Yahoo", and resets the status bar when the mouse moves out. Pretty cool, uh? On-the-fly text Text inside the document is usually static- if you reload this document 5 times, there's no reason to believe that the document's text will be any different each time...or is there? One of the coolest things about JavaScript is that it allows you to generate text on the fly. You could, for example, have the document greet you "Good morning" in the morning, and "Good night" at night. The basic way to write out text in JavaScript is by using the document.write() command, as follows: <script> document.write('Some text')
  • 3. </script> Whatever you put inside the parentheses, JavaScript displays it on the page. Taking this basic idea one step further, I'll create a script that writes out the last modified date of this page. <script> var modifieddate=document.lastModified document.write(modifieddate) </script> The above is a perfect example of "on-the-fly" text. The text reflects the last modified date of your page, and is updated automatically whenever you edit the page and save it! JavaScript dialog boxes So, what the heck are JavaScript dialog boxes? Well, they are interesting little "pop-up" boxes that can be used to display a message, ask for confirmation, user input etc. They're very easy to create, not to mention cool! Three types of dialog boxes exist in JavaScript- alert, confirm, and prompt. I'll show you an example of each: Alert: <script> alert("Welcome, my friend!") </script> Confirm: <script> var answer=confirm("Jump to CNN?") if (answer) window.location="http://cnn.com" </script> Prompt: <script> var answer=prompt("Please enter your name") alert("Hello "+answer) </script> All of the boxes allow you to customize the message simply by entering in a different text inside the function's parentheses. Go ahead, try it now on your web page! Image submit button JavaScript is not only practical, it's cosmetical as well! If you work with HTML forms (and who doesn't?), then you should agree that form buttons are probably one of the most ugly things ever to exist inside a browser. They're dull, ugly, and desperately need a make-over! Well, with the help of JavaScript, it's actually possible to use a custom image in place of form buttons to perform the important task of sending the form's content to you. Here's how:
  • 4. 1) Give your form a name: <form name="andy"> " </form> 2) Replace the usual submit button (<input>) with the below: <form name="andy"> " <a href="javascript:document.andy.submit()"><img src="myimage.gif"></a> </form> That's it. For the submit button, noticed that I used an image link with an unusual url: javascript:document.andy.submit(). This line of code tells JavaScript to submit the form named andy when the link is clicked on. Here's an actual example of a form with an image submit button: Name: Email: Displaying a random message/ image I get a lot of emails asking me stuff like: "How do I display a random quote on my page?", or "Is it possible to have a random image show up each time the surfer reloads the page?" The answer? No problemo! JavaScript can be used to easily accomplish just that. The below's a "random" quote example, where a quote out of three is randomly displayed each time this page is loaded (Reload this web page to see another quote): Here's the source code used: <script> var whichquote=Math.round(Math.random())*3 if (whichquote<=1) document.write('"You can take away my life, but you can never take away my freedom!"') else if (whichquote<=2) document.write('"I'll be back"') else if (whichquote<=3) document.write('"You can count on it"') </script> The key here is the code: var whichquote=Math.round(Math.random())*3 I'll explain this code by breaking it down: Math.random() is a JavaScript method, and always
  • 5. generates a real number between 0 and 1. Math.round() rounds that number to an integer. By multiplying that number by 3, I always get a random number that's between 0 and 3. Why 3? Because I have three quotes I want to randomly display, so I need three random "slots". If you have 5 quotes, just multiple the code by 5 instead. Now, quotes are great, but what if you want to display a random image? Simple. Just change the text to the <img> tag: <script> var whichquote=Math.round(Math.random())*3 if (whichquote<=1) document.write('<img src="first.gif">') else if (whichquote<=2) document.write('<img src="second.gif">') else if (whichquote<=3) document.write('<img src="third.gif">') </script> Don't you just love JavaScript? Advanced JavaScript applications Ok, I'll dedicate this final tutorial to showing you some more advanced JavaScript applications, along with their complete source code, so you can simply cut and paste 'em to instantly "pump up" your site! JavaScript live clock This is a cool script that displays a "live" form clock on your web page: 5:50:32 PM Source code: <form name="time"> <input type="text" name="time2" size=15> </form> <script> function liveclock(){ var curdate=new Date() var hours=curdate.getHours() var minutes=curdate.getMinutes() var seconds=curdate.getSeconds() var suffix="AM" if (hours>=12){ suffix="PM" if (hours>=13) hours-=12 } if (minutes<10) minutes="0"+minutes if (seconds<10)
  • 6. seconds="0"+seconds var thetime=hours+":"+minutes+":"+seconds+" "+suffix document.time.time2.value=thetime setTimeout("liveclock()",1000) } liveclock() </script> Image Flip An image flip is a cool JavaScript effect that makes an image change to another when the mouse moves over it. Not very practical, but defintely cool: The above button consists of two images - one before the mouse is over it, and one after. Here's the source code: Source code: <a href="index.htm" onMouseover="if (document.images) document.images.menu.src='after.gif'" onMouseout="if (document.images) document.images.menu.src='before.gif'"><img src="before.gif" name="menu" border=0></a> Try pasting the above code onto your webpage, and change 'before.gif' and 'after.gif' to reflect your own images. Notice how I gave the image a name ('menu') using the name attribute. This is neccessary, and if you want to have multiple image flips on one page, you'll need to give each image flip a unique name. Drop down menu box I'ms sure most of you have seen a drop down menu box before. They are <select> lists that go to the selected url when clicked on...a great space saver! Geocities GO <form name="c1"> <p><select name="c2" size="1"> <option selected value="http://www.geocities.com">Geocities</option> <option value="http://www.happypuppy.com">Happypuppy</option> <option value="http://www.gamespot.com">Gamespot</option> </select> <input type="button" value="Go" onClick="location=document.c1.c2.options [document.c1.c2.selectedIndex].value"></p> </form> You can cram in as many links as you wish into the box simply by adding more options to the selection list.
  • 7. Recommended JavaScript sites: Website Abstraction- A superb JavaScript technology center featuring free scripts and tutorials on many aspects of JavaScript. I credit most of my JavaScript knowledge to this site. Dynamic Drive- Quite an amazing JavaScript site with advanced JavaScripts/DHTML scripts you can simply cut and paste onto your site to intantly add magic to your site. I must have used at least a dozen of them on my personal site already...