Javascript Lesson 5

Goto Lesson:

Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Writing to the Page

Now lets learn some simple Javascript functions that allow you to actually do stuff to the page. We will start with writing stuff to the page. In order to write stuff to the page. You must first access the document and then perform the writeln function. This is one of the functions that does not belong in the head, but instead where you want it appear, like the following:

<script language="Javascript>
<!--hide
document.writeln("hello everyone");
//end-->
</script>


Whatever you put in the parenthesis is printed to the page. If it is text it must be in quotes, but if it is a variable to not put it in quotes and it will print the value.

Alerts

The alert function forces a error window to pop up and display a window to the user with an ok button. It works pretty much the same as the writeln command except you do not have to access the DOM. The code is usually in the head and you must go into Javascript mode.

alert("this is an example of a pop-up");

This will produce a pop up window that says what is in the parenthesis. You can also put a variable in the parenthesis as long as you have no quotes. It will then put the value of the variable in the pop-up message.

Prompts

Now lets say you want to ask the user for some information when they come to your page like maybe your name. You would want to use a prompt, the code would once again go into the head. You must put in the question and then a default value for the answer(you would leave this blank for none). You always want to set the answer equal to something so you set a variable equal to the function which will in turn set it equal to the answer.

var answer=prompt("What is your name?","Visitor");

this would cause a pop up to come up and ask for the visitors name and visitor will already be entered for them and they could delete this and type a new name if they desired to. Then what they enter is set as the value for the variable answer.

Putting it all together

All the information you learned in this lesson can be used to add personalization to your page. Try entering the following code and see how it works.

<scriptlanguage="Javascript">
<!--hide me
var message="Welcome to my Javascript web page";
alert(message);
var name=prompt("What is your name?","");
document.writeln("Welcome"+name+", hope you enjoyed your visit");
//end-->
</script>


You can see from this example that you can put multiple things in the same alert message using + signs to add them. That is the end of this lesson and the end of this intro. There is much much more to learn about Javascript such as image swapping, cookies, using forms, etc. Proceed to the next page to learn about where to go from here.

Where next...