User Input and Output in JavaScript
 
 

Working with any dynamic language requires the ability to read, process and output user data. JavaScript is especially useful when you want to take user information and process it without sending the data back to the server. JavaScript is much faster than sending everything to the server to process, but you must be able to read user input and use the right syntax to work with that input.  This article will focus on retrieving user input and displaying it on the screen through HTML elements or prompts. 

Displaying Prompts and Retrieving User Responses

JavaScript has a few window object methods that you can use to interact with your users. The prompt() method lets you open a client-side window and take input from a user. For instance, maybe you want the user to enter a first and last name. Normally, you can use an HTML form for user input, but you might need to get the information before sending the form back to your server for processing. You can use the window.prompt() method for small amounts of information. It's not meant for large blocks of text, but it's useful when you need information before the user continues to another page.

The following code is an example of the window.prompt method. 

var customerName = prompt("Please enter your name", "<name goes here>");

if (customerName!= null) {

    document.getElementById("welcome").innerHTML =

    "Hello " + customerName + "! How are you today?";

}

The first line of code uses the prompt method. Notice that we don't need the "window" object since JavaScript inherits the main DOM methods and understands that this is an internal method. The first parameter in the prompt is what you want to show the user. In this example, we want the user to enter a name, so the prompt displays "Please enter your name." The second parameter is the default text. This default text helps the user understand where to type the name, but if he clicks "OK" without entering a name, the "<name goes here>" text will be used for the username. You can create checks in your JavaScript code that detects when the user doesn't enter a name and just clicks OK, but this code assumes any text entered is the user's name. 

Notice the "if" statement that checks if the "customerName" variable is null. This logic checks to make sure that the user entered something. It only checks that some character was entered, so the user can type anything to bypass the "if" statement. The code within the "if" statement then displays the message to the user in the "welcome" div. We've covered reading and writing text to a web page, and this is another example of writing text to the inner HTML section of a div. Remember that the innerHTML property writes any tags or text within the opening and closing div tag.

Use this method to get a short string response from your users before they access a page or before they move on to another page in your site structure.

The JavaScript Confirmation Message Box

The window.prompt method is one way to read user input, but JavaScript also provides a way to get confirmation from the user. For instance, you might want to confirm that the user has entered the right information and wants to continue with payment. The confirmation window displays the amount the user will be charged, and the user has the option to confirm or cancel. You could write a complex JavaScript function to create a new window for confirmation or you can use the internal window.confirm method. This method returns either a boolean true result if the user clicks "OK" or the boolean false result if the user clicks "Cancel." This prompt is a quick way to get confirmation without using any complex coding logic.

Look at the following JavaScript code.

var r = confirm("Are you sure you want to send a payment?");

if (r == true) {

    x = "Payment sent!";

} else {

    x = "Payment cancelled!";

}

alert (x);

The main utility in the above code is the "confirm" function. This is an internal JavaScript function from the window object. In other words, using "window.confirm()" and "confirm" results in the same function. JavaScript handles the inheritance for you, so you don't need to remember to use the window object. The confirmation window is also pre-built and shown to the user. In this example, a prompt displays with the text "Are you sure you want to send a payment?" The only options for the user are to click the Cancel button or the OK button. OK is the confirmation that returns "true." If the user clicks "OK," the variable x contains the text "Payment sent!" Conversely, if the user clicks the "Cancel" button, x contains the text "Payment cancelled!" The text is then displayed to the user using the "alert" function. This is the first time we've seen the alert function, which is also a part of the window object. Typing "alert" and "window.alert" results in the same method call. The alert prompt is common during debugging and development of a web application, because it's a quick way to check your logic and see the control flow of your code. The alert function in this example checks that the confirm window is responding with the right result and the x variable contains the right text.

Displaying Text from User Input

There are three main HTML tags used to display text after you prompt users. You've seen two internal JavaScript functions that get user input, but how do you display it back to the user? The three tags used are the div, span and text tags. The third one, the text tag, is a form field used to take string input from the user. You usually use this tag to get input such as a name or an address, but you can also display input from the user.

The span and div tags are a way to just display the information you've read in JavaScript prompt windows. You can also display data you've retrieved from a database.

Let's use the previous example where we prompted the user to enter a name. We then use the input to display output in a div element. We've seen this before, but this is the first time we've used input directly from the user.

<!DOCTYPE html>
<html>

<head>

<script> 

var customerName = prompt("Please enter your name", "");
if (customerName!= null) {
    document.getElementById("welcome").innerHTML =
    "Hello " + customerName + "! How are you today?";
}

</script>

</head>

<body>

<div id="welcome">My First JavaScript code.</div>

</body>
</html>

We've included the HTML this time to show you how JavaScript prompts work with HTML elements. The element we're using is the div HTML tag with the id of "welcome." The JavaScript prompt asks the user for his name and then displays the result in the "welcome" div. You can also use this same code to display the result in the span element using the same code except change the div tag to a span opening and closing tag. 

You've seen the innerHTML property several times, which controls the text within the opening and closing div or span tags, but what if you want to use the input to pre-populate a form field? The input text field lets users input string values, but you can use the methods we've seen to pre-populate string values automatically. Using the same input example as we previously used, the following code uses the input prompt to enter the user's name in the "username" text field. 

<!DOCTYPE html>
<html>

<head>

<script> 

var customerName = prompt("Please enter your name", "");
if (customerName!= null) {
    document.getElementById("username").value = customerName;
}

</script>

</head>

<body>

Interested in learning more? Why not take an online JavaScript course?

<input type="text" id="username" />

</body>
</html>

The above code varies slightly from the previous div example. This code uses the same prompt method to get a user's name, but then it displays the information in an "input" element with the type set as "text." Again, you'll notice that the id tag property is used, which allows us to grab the DOM element by id and change its properties. The form input element uses the "value" property and not the innerHTML property. You'll get to know the DOM element properties by heart as you use them more frequently. Also notice that the input HTML tag does not have a closing tag. The terminator "/>" can be used when you don't need to contain text within an opening and closing tag. Using the terminator is cleaner and follows HTML5 standards. 

JavaScript is used to manipulate the UI in a web application, so this next section is an important look at taking user input and using that input to change elements. You'll use this functionality often as you work with JavaScript and HTML pages.

Managing Web Page Styles using JavaScript and CSS

We've covered displaying output to a user and reading input from window prompts in JavaScript. One benefit of using JavaScript is integrating it with CSS. CSS files contain the styles for your web page, and JavaScript lets you change these styles dynamically. For instance, you might want to change the color of some text when the user hovers the mouse over a paragraph or display a drop-down menu when a user clicks a button. These types of actions are possible using CSS and JavaScript. Both of these languages work together to make fast, client-side UIs. This article covers some of the basics when working with CSS and JavaScript. 

What is CSS? 

Cascading Style Sheets have long been the design part of a web page. HTML is the code base, but CSS styles the elements. Whether it's styling link colors, font size, or div location on the page, CSS does the work for you. The CSS language separates coding from design, so you can apply styles to several sites without any additional code. Plug in the CSS page and let the style sheets do the design for you. You can also work with a designer who can work with CSS to style your site while you create the code. 

Using Element Classes 

CSS uses classes just like other object-oriented languages. CSS lets you define a class that you then insert into your HTML. The classes can be used by name in your HTML using the "class" property defined in most HTML tags. Let's take an example of a CSS class in the code below. 

p {
    text-align: center;
    color: green;
}

In the above CSS class, a design is set for the HTML "p" tag. The CSS style names and syntax take some time to get used to, but this specific example aligns the paragraph's text to center and changes the font color to green. The problem with this code is that all paragraph elements will have the same design. To overcome this limitation, you can create the same CSS class style with a class name instead of encompassing all p tags. 

The following code is an example of the same class except it's given a name. 

.center {
    text-align: center;
    color: green;

In this example, only elements that use the "center" class will incorporate the center text alignment and green font. The following HTML page shows you how to use a CSS style. 

<!DOCTYPE html>
<html>

<head>

<style> 

.center {
    text-align: center;
    color: green;
}

.center_black {
    text-align: center;
    color: black;
}

</style>

</head>

<body>

<p id="username" > Hi, user! </p>

</body>
</html>

Notice the "style" tag contains the "center" class we created. You can also use external CSS files and link them in your pages. In the above example, we created a paragraph and assigned it the "center" class using the "class" property. Classes in CSS are denoted with the period in front of the class name. That's all it takes to link CSS styles with your HTML elements. A second class named "center_black" is set with the same properties as "center" except the text is black. You can use JavaScript to dynamically change styles between the "center" class and the "center_black" class. 

If you remember, we used the "getElementById" method several times to point the JavaScript code to a specific HTML element. You can do the same with changing CSS class properties. Look at the following JavaScript code. 

document.getElementById("username").className = "center_black"; 

This one line of code changes the applied class from "center" to center_black. Usually, you change a class after a certain event from the user. For instance, you might want to change the class based on when the user hovers the mouse over the paragraph. We discussed events in a previous chapter. When the user hovers the mouse over an element, the "onmouseover" event fires. You can override this event and set your own function. In this case, you override the onmouseover event and set it to a JavaScript function that changes the CSS class. The following code is an example that builds on the previous code sample. 

<!DOCTYPE html>
<html>

<head>

<script> 

function ChangeStyle ( )
{
    document.getElementById("username").className = "center_black";
}

</script>

<style> 

.center {
    text-align: center;
    color: green;
}

.center_black {
    text-align: center;
    color: black;
}

</style>

</head>

<body>

<p id="username" onmouseover="ChangeStyle()"> Hi, user! </p>

</body>
</html>

The styles and paragraph code are the same except a JavaScript function was added and the "onmouseover" event inserted into the paragraph HTML tag. The onmouseover event calls the JavaScript function "ChangeStyle." When the user hovers the mouse over the paragraph, the text color changes to black.  This example is one of numerous dynamic changes you'll need to create when working with CSS and JavaScript. 

Working with CSS3, Animation and Transition Effects

Years ago, the only way to create dynamic animations was to use Adobe Flash. HTML5 and CSS3 allow you to quit Flash and use native programming for any browser. Your users no longer need to install plugins or update Adobe Flash to run your website. Instead, you can integrate JavaScript with CSS transition styles that animate objects using a process called transitions.

Transitions use animated images or shapes when a user hovers over an HTML element or clicks a button. For instance, you might want to expand a text box across the page when a user hovers over it. Instead of showing the smaller box and then the larger box, the transition CSS styles and JavaScript displaying a growing box that expands slowly using animation.

Let's take the following HTML example.

<!DOCTYPE html>
<html>

<head>

<style> 

div {
    width 2s;  
    transition: width 2s;
}

div:hover {
    width: 300px;
}

</style>

</head>

<body>

<div id="username"> Hi, user! </div>

</body>
</html>

The power of this div element is in the "div" CSS class. The first class specifies the amount of time for the transition. In this example, the transition happens in 2 seconds. The first class only specifies the transition time, but the second div class specifies the width of the expansion. The div expands from its current state to 300 pixels in 2 seconds. 

We can change this underlying CSS style to only occur when the user sends us input. For instance, you might want to apply a transition when a user clicks a button. You can do this by using JavaScript, overriding the "onclick" event and changing the CSS style on-the-fly. Here is an example of how you can use transition styles with JavaScript. 

<!DOCTYPE html>
<html>

<head>

<style> 

.changewidth {
    width 2s;  
    transition: width 2s;

    width: 300px;
 

</style>

<script> 

function ChangeStyle ( )
{
    document.getElementById("username").className = "changewidth";
}

</script>

</head>

<body>

<div id="username"> Hi, user! </div>

<button id="clickme" onclick="ChangeStyle()"> Click Me! </button>

</body>
</html>

We've used the "onclick" event before. In this example, the same "ChangeStyle()" function is called as the previous example. However, this time the JavaScript function changes the style to the "changewidth" class. We used the same CSS properties, which changes the "username" div from the current width to a width of 300 pixels. 

So far, we've used inline CSS styles, but this means that you need to change all of your web pages to effectively make global changes to all of your styles. This type of coding is inefficient, because you can forget pages, make typos when changing too many pages, and insert CSS syntax or bug errors accidentally. To eliminate the chance of errors and make your changes global, it's better to insert a CSS style page into your website code. You save all of your CSS styles in a text file, store it on your web server, and link the style sheet to your HTML page. When you make changes to a CSS class in the external file, all HTML files that link to your CSS file also change. One CSS file and associated changes affect all of your HTML files without editing any of the internal HTML code. The following HTML code is from a previous example except the CSS file is stored externally and linked using the "link" tag. Take note that the link tag is inserted in the head section with the JavaScript code. 

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="mystyle.css"> 

<script> 

function ChangeStyle ( )
{
    document.getElementById("username").className = "changewidth";
}

</script>

</head>

<body>

<div id="username"> Hi, user! </div>

<button id="clickme" onclick="ChangeStyle()"> Click Me! </button>

</body>
</html>

Notice the CSS inline styles are eliminated from the code. The styles are saved in a CSS file named "mystyles.css." The link tag then links the file to your HTML code where you can call any class. You should use external files for both JavaScript and CSS functions and classes. 

We covered a few CSS classes and events you can trigger to dynamically change styles. JavaScript has several methods and events that you can use to change CSS styles with only a few lines of code.