Ken Ward's JavaScript Tutorial 2

Ken Ward's New Java Script Tutorial

Pop-up alert code

In the last lesson we demonstrated a pop up alert. In this one we explain and state the code used to make alerts.


Computer Contents

Ken Ward's Java Script Tutorial 2

In the last lesson we learned that we always put the code between these tags:

<script type="text/javascript">

<!--//

The code goes here

//-->

</script>

While various other script attributes work fine, we should really use the following:

<script type="text/javascript">

Because the browser always assumes your code is JavaScript, unless you tell it different, the bare script tags work with JavaScript. But it's good practice to be specific and tell it exactly what script you are using. Future browsers may behave differently. For XHTML, we MUST use the tags as described.

Now for the code for the alert box. But first, let's look at the form:

<form action="">

<input type="button" value="Press Me" onclick="alert1()" />

</form>

The form is a normal HTML form with a button. The only difference is the onclick part. We have the code:

onclick="alert1()"

The part in blue is what JavaScript calles a function. Or, really it's the name of a function. We know it is a function because of the () - two brackets at the end. This always means it's a function. The function is only a name and we have to give it a some code, or a set of instructions. This code is in the <head></head> part of the document. Here is the code:

<script type="text/javascript">

<!--//

function alert1()

{

alert("You clicked me!");

}

//-->

</script>

The actual bit of code is simple. It is:

alert("You clicked me!");

The bit in commas is the message we want the alert to display, and the line ends with a semi-colon, as JavaScript usually does. So that's it. You have a form button. It has an onClick which calls the function alert1() and this function is set out in the head of the document as shown above. Don't forget the curly brackets, though!

exclam.gif (342 bytes)In old HTML, you could write onClick in various ways. Sometimes ONCLICK. HTML is not case sensitive. It doesn't care how you write onClick. But JavaScript is case sensitive. It does care. When you write words inside <script> tags then you must write them correctly, case and all. If the form is called Form, then JavaScript will not recognise form as being the same! In future, I will write the words in JavaScript style.

Nowadays, however, to be compatible with XHTML, we MUST write "onclick" in lowercase letters. All attributes in the tags MUST be lowercase to be compatible with the future.


Why not write some alert buttons for yourself and put in your own messages!

Next, let's learn how to enter a new line in JavaScript


Contents

[If you need to learn more about HTML visit the HTML Tutorial]

I am always pleased to hear from you.
Send your comments to