Every topic starts at New. Sign in and your practice counts.
If a school wants to display the result of each student on their website, it would have to create a different static webpage for each student, and the job of managing those pages only grows as the number of students grows. The solution is a dynamic website: one whose content changes according to user input, rather than a separate static page per case. A dynamic website like this can be created using JavaScript together with HTML and CSS.
Recall the earlier code that printed the index numbers 0-9 in a loop. That same code can be extended with a new function, descOrder(), which prints the index numbers in descending order when it is called. The extended program adds an element with the id dynamicContent and a button that calls descOrder() when pressed.
<html>
<body>
<script type="text/javascript">
var index;
document.write("For-Loop Starts After This ... <br />");
for(index = 0; index < 10; index=index+1){
document.write("Index No. : ", index, "<br />");
}
document.write("For-Loop Stopped!");
function descOrder () {
for(index = 10; index > 0; index =index -1){
document.write("Index No. : ", index, "<br />");
}}
</script>
<p id="dynamicContent">Click the button to change output to Descending Order.</p>
<button onclick="descOrder()">Descending Order</button>
</body>
</html>
When the webpage first loads, the index numbers are printed in ascending order and the button appears below them. Pressing the button calls descOrder(), which reprints the index numbers in descending order instead, replacing the earlier output. This is what makes the page dynamic: the same loaded page changes its own content in response to user input, without reloading from the server.
The page's content can be changed in other ways too, not just its text. Adding a line like:
document.body.style.backgroundColor = "peachpuff";
after the loop, then saving the file, refreshing the page and pressing the button, changes the background color of the page as well as the index list. document refers to the whole HTML page, body refers to the visible content, and the style property lets a script set an element's properties dynamically, such as changing the page's background color. As an activity, try adding a second button that separates out the background-color change into its own function.
This topic builds on the website and JavaScript foundations covered earlier in the chapter, so the recap below spans that whole arc rather than only this topic's own dynamic-content example.
< and >, together with the characters between them, is called a tag.prompt() function, which pops up a message window similar to alert().for loop starts with an initial index value and iterates until its terminating condition is met, adjusting the index by its step size each time. A loop placed inside another loop is a nested loop.descOrder() above) that a program needs to run more than once.