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.
Open the starter document for the “Fireside Chat.”
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.
Add opening and closing <p> tags inside the quotes. Add a style statement and style the text as you like.
Above the "document.write" line, add a variable statement to hold the reader's name: var name=prompt("Please type your name.");
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>");
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>");
}
To make a function out of the statements, add opening and closing <script> tags to the <head>.
Create the function by writing:
function writeName() {
place code here
}
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.
Program the button at the bottom of the page to print the page.
Add a function to the <script> tag in the <head>: function printPage() { this.window.print();
}
Call the printPage function by linking it to the “Print” button: <button onClick="printPage()">Print</button>
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.
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";
}
Link the function to the “Grey” button: <button> onClick="colorGrey()">Grey</button>
Create a similar function to change the text color back to black.