The University of Texas at Austin- What Starts Here Changes the World
Services Navigation


Example 1 - Hello in Javascript

Let's start simple. This frst example will prompt a user for their name and favorite color. It will then display their name in the Web pages and change the background color of the page to be the color they chose. While this may not be the most compelling example, it will introduce several important Javascript concepts.

<HTML>
<HEAD>
<TITLE> Hello World in Javascript </TITLE>
</HEAD>
<BODY>
<h2>Example 1</h2>

<script language="Javascript">
// Hello in Javascript


// display prompt box that ask for name and 
// store result in a variable called who
var who = window.prompt("What is your name");

// display prompt box that ask for favorite color and 
// store result in a variable called favcolor
var favcolor = window.prompt("What is your favorite color");

// write "Hello" followed by person' name to browser window
document.write("Hello " + who);

// Change background color to their favorite color
document.bgColor = favcolor;

</script>


</BODY>
</HTML>

Javascript code is embedded into HTML documents and normally appears between <script> and </script> tags. Javascript statements can also appear within existing HTML tags as attributes. We will see that in another example.

Several important things to note about Javascript:

  • Javascript is case sensitive, document.write is differnt than Document.Write
  • Javascript statements appear between <script> tags. Because there are many scripting languages, you should identify the language as Javascript as shown in the example above
  • Javascript statements end with a semi-colon
  • You can include comments in your Javascript code by beginning the line or lines with // characters

The window.prompt line will display a dialog box on the screen with the quoted string. Javascript stores the user input from this dialog box in the specified variable.

The document.write line writes the specified text into the browser window. You can use document.write to write text, HTML, or the values of variables into the page at a given point. Notice that Example 1 writes both the word "Hello" and the value of the who variable. The plus character (+) is used to concatenate text values or quoted strings.

Test Example 1

 


  Updated 2003 September 29
  Comments to www@www.utexas.edu