Andy's JavaScript tutorial 1 Andy's JavaScript tutorial 2 Andy's JavaScript tutorial 3 JavaScript tutorial
 



An Idiots Guide to 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 incredibly 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 really long boring answer:

Short answer: Interesting stuff. Just because. 1-2 weeks. Yes (well alright it's not imperative).

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 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 actual JavaScript 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 (that's the code thingy 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>

 

[FrontPage Save Results Component]

Confirm:

<script>
var answer=confirm("Jump to CNN?")

if (answer)
window.location="http://cnn.com"
</script>

 

[FrontPage Save Results Component]

Prompt:

<script>
var answer=prompt("Please enter your name")
alert("Hello "+answer)

</script>

[FrontPage Save Results Component]

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 visually appealing 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="dragonhive">
"
</form>

2) Replace the usual submit button (<input>) with the below:

<form name="dragonhive">
"
<a href="javascript:document.dragonhive.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?

1

 

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 them to instantly improve your site!

JavaScript live clock

This is a cool script that displays a "live" form clock on your web page:

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 definitely 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'm 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!

 

<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.

 

Well that brings us to the end of the Idiots Guide to JavaScript if you still are struggerling I can no longer help you but you might want to check out the the JavaScript Kit or you can look at my other guide to JavaScript, click here.

 

1643273-20