Previous Page
Next Page

Hack 10. Generate a Styled Message with a CSS File

Let the users choose predesigned styles for the messages they see.

This hack sends a request to a server, which returns a text message. The user's choices determine the actual message content and appearance. The HTML for the page includes a select tag listing the styles the users can choose for the display of the results and a text field containing a partial URL they can complete and submit to a server.

The information returned relates to the response headers returned by the server [Hack #9]. However, what we are interested in here is this hack's dynamic message generation and style assignment. Here's the HTML code for the page:

    <script type="text/javascript" src="js/hack8.js"></script>
    <script type="text/javascript">
    function setSpan(  ){
        document.getElementById("instr").onmouseover=function(  ){
        document.getElementById("instr").onmouseout=function(  ){
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>view response headers</title>
    <link rel="stylesheet" type="text/css" href="/parkerriver/css/hacks.css" />
<body onload="document.forms[0].url.value=urlFragment;setSpan(  )">
<h3>Find out the HTTP response headers when you "GET" a Web page</h3>
<h4>Choose the style for your message</h4>
<form action="javascript:void%200">
        <select name="_style">
            <option label="Loud" value="loud" selected>Loud</option>
            <option label="Fancy" value="fancy">Fancy</option>
            <option label="Cosmopolitan" value="cosmo">Cosmopolitan</option>
            <option label="Plain" value="plain">Plain</option>
    <p>Enter a URL: <input type="text" name="url" size="20" onblur=
            "getAllHeaders(this.value,this.form._style.value)"> <span id=
            "instr" class="message">&#171;press tab or click outside the field 
            when finished editing&#187;</span></p>
    <div id="msgDisplay"></div>

The purpose of the setSpan( ) function defined within the web page's script tags is to give some instructions ("press tab or click outside the field when finished editing") a yellow background when the user passes the mouse pointer over them.

Before I describe some of the code elements, you may be interested in how the web page appears in a browser. Figure 1-15 shows this window.

Figure 1-15. Choose your style

The CSS styles used by this web page derive from a stylesheet file named hacks.css. When the user chooses a style (say, "Cosmopolitan") from the select list, enters a value in the text field, and then tabs out of or clicks outside of the field, that user's chosen style is dynamically assigned to the container that will hold the message (a div element with id msgDisplay).

Here is the hacks.css stylesheet:

div.header{ border: thin solid black; padding: 10%;
 font-size: 0.9em; background-color: yellow; max-width: 80%}

span.message { font-size: 0.8em; }
div { max-width: 80% }

.plain { border: thin solid black; padding: 10%;
 font: Arial, serif font-size: 0.9em; background-color: yellow; }
.fancy { border: thin solid black; padding: 5%; 
 font-family: Herculanum, Verdana, serif;
 font-size: 1.2em;  text-shadow: 0.2em 0.2em grey; font-style: oblique;
 color: rgb(21,49,110); background-color: rgb(234,197,49)}
.loud { border: thin solid black; padding: 5%; font-family: Impact, serif;
 font-size: 1.4em; text-shadow: 0 0 2.0em black; color: black; 
background-color: rgb(181,77,79)}
.cosmo { border: thin solid black; padding: 1%; 
 font-family: Papyrus, serif;
 font-size: 0.9em; text-shadow: 0 0 0.5em black; color: aqua; 
 background-color: teal}

The stylesheet defines several classes (plain, fancy, loud, and cosmo). A class in a CSS stylesheet begins with a period (as in .fancy) and defines various style properties, such as the font family and background color. Using this technique, your CSS experts can define the actual styles in one place, for use in multiple web pages. Clearly, an experienced designer would have some, ah, differences with the style-attribute choices here, but please bear with me!

The Ajax-related JavaScript code can assign the predefined styles to page elements based on user choices. Therefore, the presentation tier of your web application is separated from the application logic or domain tier.

The onblur event handler for the text field submits the URL value and the style name to a function named getAllHeaders( ):


The reference this.form._style.value is JavaScript that represents the value of the option chosen from the select list (the style name). The reference this.value is the text entered by the user in the text field.

Here is the JavaScript code that the page imports from hacks8.js, with the code that dynamically assigns the style to the displayed message highlighted:

var request;
var urlFragment="http://localhost:8080/";
var st;

function getAllHeaders(url,styl){

//event handler for XMLHttpRequest
function handleResponse(  ){
        if(request.readyState == 4){
            if(request.status == 200){
                /* All headers received as a single string */
                var headers = request.getAllResponseHeaders(  );
                var div = document.getElementById("msgDisplay");
                div.className= st == "" ? "header" : st;
            } else {
                //request.status is 503 if the application isn't available; 
                //500 if the application has a bug
                alert("A problem occurred with communicating between "+
                      "the XMLHttpRequest object and the server program.");
        }//end outer if
    } catch (err)   {
        alert("It does not appear that the server is available for "+
              "this application. Please"+
              " try again very soon. \\nError: "+err.message);


/* See Hacks #1, #2, and others for definitions of the httpRequest(  )
 and initReq(  ) functions; snipped here for the sake of brevity. */

Easy as Pie

The getAllHeaders( ) function sets a top-level st variable to the name of a CSS style class (plain, fancy, loud, or cosmo). The code then sets the className property of the div that holds the message in a shockingly simple way, which changes the style assigned to the message:

if(request.status == 200){
    /* All headers received as a single string */
    var headers = request.getAllResponseHeaders(  );
    var div = document.getElementById("msgDisplay");
    div.className= st == "" ? "header" : st;

If for some reason the choice of class name derived from the web client is the empty string (it cannot be here because the select tag only contains complete string values), the div element is assigned a default style class name of header.

This JavaScript could potentially be imported into another client web page, so you have to include some checks for invalid input values.

The hacks.css stylesheet also defines the header class.

The following figures are examples of the same message assigned different styles by the user. Figure 1-16 shows the result if the user selects the "Cosmopolitan" style.

Figure 1-16. A Cosmopolitan-styled message

Figure 1-17 depicts an alternate style.

Figure 1-17. Alas, a Plain-styled message

Previous Page
Next Page