Summary: An exercise to create a page that customizes itself depending on input from the user.
Prerequisites: Basic experience writing HTML.
Provides:
Experience with functions, strings, prompts, and
document.write().
References: More JavaScripting
Overview:
Create a page that prompts for the user's name and then places that name somewhere on the page. It may be simpler if you begin with your pages from the previous exercise. Your page might look something like
<HTML> <HEAD> <TITLE>Experiments with JavaScript : A Custom Page</TITLE> </HEAD> <BODY> <script language="javascript"> var userName userName = prompt("Please enter your name", "") document.write("<H1>" + userName + "'s custom page</H1>") </script> <P> Since you are one of my favorite students, I've developed a custom page just for you. </P> </BODY> </HTML>
If you're likely to do the same thing again and again, it is preferable to put the code for that action into a separate function. Usually, we place functions in the head of the document. You may also want to place some variables in the head of your document.
Determine appropriate functions for your sample page, and place them
in the header. For my sample page, I noted that I expected to need
to be able to produce a level one header from a name, and created a
customTitle function. I added a few more to make it
interesting.
<HTML> <HEAD> <script language="javascript"> // We'll need the user's name at various points, so read it // here. var userName userName = prompt("Please enter your name", "") // Function customTitle() provides a custom title for the document function customTitle(nm) { document.write("<H1>" + nm + "'s custom page</H1>") } // customTitle // Function sillyParagraph() provides a "silly" paragraph using // someone's name. function sillyParagraph(nm) { document.write("<P>" + nm + ". "); document.write("Bo B" + nm.substring(1,nm.length) + ". ") document.write("Banana fana fo F" + nm.substring(1,nm.length) + ". ") document.write("Fee fie mo M" + nm.substring(1,nm.length) + ". ") document.write(nm + ". </P>") } // sillyParagraph </script> <TITLE>Experiments with JavaScript : A Custom Page</TITLE> </HEAD> <BODY> <script language="javascript"> customTitle(userName) </script> <P> Since you are one of my favorite students, I've developed a custom page just for you. </P> <script language="javascript"> sillyParagraph(userName) sillyParagraph("Sam") </script> </BODY> </HTML>
Finally, move your function definitions to a library file and load that library file. I haven't included sample code here, since you should be figure it out from our past examples.
This page created Wed Jun 11 14:30:19 1997 by SamR's Site Suite.