JavaScript Fireside Chat

Using a Variable, Conditional Statement, and Function

In this section we will see how to write JavaScript code, include a conditional statement, and place the code into a function so it can be used multiple times.

  1. Open the starter document for the “Fireside Chat.”
  2. Inside the <div id="livearea">, place opening and closing <script> tags and add the code:
    document.write("Welcome to the Fireside Chat web page.");
    Note that the text is written below the heading.
  3. Add opening and closing <p> tags inside the quotes. Add a style statement and style the text as you like.
  4. Above the "document.write" line, add a variable statement to hold the reader's name:
    var name=prompt("Please type your name.");
  5. Add the variable name to the statement by placing it outside the quotes and connecting it to the text with “+” signs:
    document.write("<p style="font-family: Georgia;">Welcome to the Fireside Chat web page, " + name + "</p>");
  6. If the reader does not type a name, the statement will print with a blank. To prevent the statement from printing if the user does not enter a name, place the “document.write” statement in a conditional “if” statement:
    if (name!="") {
    document.write("<p style="font-family: Georgia;">Welcome to the Fireside Chat web page, " + name + "</p>");
    }
  7. To make a function out of the statements, add opening and closing <script> tags to the <head>.
  8. Create the function by writing:
    function writeName() {
    place code here
    }
  9. Call the function by keeping the <script> tags in the <body> and writing:
    writeName();

Making a Print Button

In this section we will create a function to print the page and link it to a button. Adding an “@media” query will enable fitting the document on a letter-size page and omitting the buttons from the print.

  1. Program the button at the bottom of the page to print the page.
  2. Add a function to the <script> tag in the <head>:
    function printPage() {
    this.window.print();
    }
  3. Call the printPage function by linking it to the “Print” button:
    <button onClick="printPage()">Print</button>
  4. Add an @media print {} query to confine the page to 8.5x11" and hide the buttons in the print view:
    @media print {
    body {
    transform: scale(0.85);
    } #page {
    width: 8.25in;
    height: 10.0in;
    } footer {
    display: none;
    }

Using Buttons to Change Color

In this section we will link a button to a function to change color of the text.

  1. In the <script&rt; tag in the head, add a function to change color of the div “livearea”:
    function colorGrey() {
    document.getElementById("livearea").style.color="dimgray";
    }
  2. Link the function to the “Grey” button:
    <button> onClick="colorGrey()">Grey</button>
  3. Create a similar function to change the text color back to black.