Hide output areas until needed

See more about:

You write a page that does a computation, and shows the output to the user. When the page first loads, there is no output to show. You can hide the output area until it is needed.

The button below runs a script that doubles whatever number the user enters. There is no output to show when the page loads, so the output area is hidden. Only when the user enters a number and clicks the button is the output area shown.

Try it. Enter a number and click the button.

Number:

Double:

Here is the important code:

<button id="show_double">Compute</button>
...
<p id="output_area">
  Double: <span id="double_out"></span>
</p>
...
$(document).ready(function() {
  $("#output_area").hide();
  ...
  $("#show_double").click(function() {
    ...
    $("#double_out").text(x);
    $("#output_area").show('medium');
  });
});

Look at line 4. The <span> is where the output it going to go. It has an id so JavaScript code can refer to it.

The line is wrapped in a container (lines 3 to 5). The container has an id of output_area. It contains the output <span>, plus other things needed for output, like the output caption (“Double:” on line 3).

Now look at the JavaScript. Line 8 hides the entire output area when the page first loads.

Line 12 shows what happens when the page is ready to output something. Line 12 puts text into the hidden output area. Line 13 shows the entire output area at once.

You can have several pieces of output in the same output area. For example, suppose your page got some numbers from the user, and computed their average, the highest value, the lowest value, and the number of values entered. The code might look like this:

<button id="show_stats">Compute</button>
...
<p id="output_area">
  Average: <span id="average_out"></span><br>
  High: <span id="high_out"></span><br>
  Low: <span id="low_out"></span><br>
  Count: <span id="count_out"></span><br>
</p>
...
$(document).ready(function() {
  $("#output_area").hide();
  ...
  $("#show_stats").click(function() {
    ...
    $("#average_out").text(average);
    $("#high_out").text(high);
    $("#low_out").text(low);
    $("#count_out").text(count);
    $("#output_area").show('medium');
  });
});

In this case, four output values are in the same output area.


Lessons

How to...


Dogs