Every topic starts at New. Sign in and your practice counts.
A page built only with HTML and CSS shows the same content on every visit. This topic builds the JavaScript tools that add response, memory and partial refresh to such pages.
This topic teaches why JavaScript is needed for dynamic pages and how arrays, loops, functions and bullet lists are used to store data and show it on the page.
A page built only with HTML and CSS shows the same content on every visit, which suits a basic informative page.
Interaction means code that answers clicks, scrolling and form submission. A button that changes colour and a form that checks data before sending are typical examples.
Data handling means keeping and changing sets of information such as product details or user comments. Loops list items from a store of data and functions carry out calculations from user input, including drawing the result as a graph.
Dynamic update means changing part of a page without reloading the whole page, which improves involvement and performance. A news feed that adds new stories without a refresh click shows the idea and reduces repeated manual clicks for new content.
Complex interfaces such as drop-down menus, picture slideshows and live chat are built by changing the page structure with JavaScript. Adding features without attention to layout and navigation creates redundancy, when every option appears in both a main menu and a side menu.
Separate variables for each fruit soon become awkward, with one variable for apple, one for banana and one for orange. An array keeps all the fruits in a single variable, which is a better way to organise a set of similar data.
const fruits = ["apple", "banana", "orange"];
Each position has an index number that starts at 0, so apple is at 0, banana is at 1 and orange is at 2. An array can hold words, numbers or a mixture of both, and it can grow or shrink as items are added or removed.
A loop visits each element in turn when the same operation must be applied to every item. The loop below prints each fruit to the console, giving apple, banana and orange on separate lines.
for (let i = 0; i < fruits.length; i++)
{
console.log(fruits[i]);
}
The end of the array can be extended with push and shortened from the end with pop. The length property tells how many items are stored, and a for loop can walk through them all.
The next program stores the first ten positive integers in an array and adds them. A function called calculateSum holds a variable sum that starts at zero, then a for loop runs from 1 to 10, adds the counter to sum and pushes the counter into the numbers array.
<IDOCTYPE html>
<html>
<head>
<title>Sum of First 10 Integers</title>
</head>
<body>
<script>
function calculateSum() {
let sum = 0;
let numbers = [];
for (let i = 10; i <= 10; i++) {
sum += i;
numbers.push(i);
}
The second half finishes the function, builds the display strings and closes the page. It writes the list of integers into one paragraph and the total into another, and it provides a Calculate Sum button to run the function.
document.getElementById("sumDisplay").textContent = "The sum of the first 10 integers is: " + sum;
let output = "The first 10 integers are: [ ";
for (let i = 0; i < numbers.length; i++) {
output += numbers[i];
if (i < numbers.length - 1) {
output += ", ";
}
}
output += "]";
document.getElementById("numberDisplay").textContent = output;
}
</script>
<button onclick="calculateSum()">Calculate Sum</button>
<br>
<p id="numberDisplay"></p>
<p id="sumDisplay"></p>
</body>
</html>
After the calculation the first paragraph lists 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and the second paragraph shows that their sum is 55.
The shopping list page has a heading, a text box for the product name, an Add Item button and a table that shows the list. A shoppingList array holds the item names, and two functions manage adding and display.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Shopping List</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 10px;
border: 1px solid lightgray;
text-align: left;
}
</style>
</head>
<body>
<h1>My Shopping List</h1>
<input type="text" id="newItem" placeholder="Enter item name">
<button onclick="addItem()">Add Item</button>
<br>
<table id="shoppingListTable"></table>
<script>
let shoppingList = [];
function addItem() {
const newItemName = document.getElementById
("newItem").value;
if (newItemName !== "") {
shoppingList.push(newItemName);
document.getElementById("newItem").value = "";
updateShoppingListTable();
} else {
alert("Please enter an item name!");
}
}
function updateShoppingListTable() {
const table = document.getElementById
("shoppingListTable");
The continuation clears the table, writes a header row called Shopping List Items and then adds one row for each entry. Clicking Add Item checks the box, pushes non empty text into shoppingList, clears the box and refreshes the table, while empty input shows a prompt to enter an item name.
table.innerHTML = "";
const headerRow = document.createElement("tr");
const headerItem = document.createElement("th");
headerItem.textContent = "Shopping List Items";
headerRow.appendChild(headerItem);
table.appendChild(headerRow);
for (let i = 0; i < shoppingList.length; i++) {
const itemRow = document.createElement("tr");
const itemCell = document.createElement("td");
itemCell.textContent = shoppingList[i];
itemRow.appendChild(itemCell);
table.appendChild(itemRow);
}
}
</script>
</body>
</html>
The major functions associated with arrays in JavaScript are push, indexOf, toString, concat and slice.
| Method | What it does | Example result |
|---|---|---|
| push | Adds a value at the end of the array | 1, 3, 5, 7, 9, 11 |
| indexOf | Returns the index where a value is found | 5 |
| toString | Joins all elements into one comma separated string | 1, 3, 5, 7, 9, 11, 2, 4, 6, 8, 10 |
| concat | Merges two arrays into one | 1, 3, 5, 7, 9, 11, 2, 4, 6, 8, 10 |
| slice | Creates a new subset array from the original | 5, 7 |
oddNumbers = [1, 3, 5, 7, 9];
oddNumbers.push(11);
oddNumbers.indexOf(11);
combinedArray.toString();
The doctor appointment example is modified to use an unordered list for several pricing packages.
An unordered list uses the ul element and shows bullets such as squares or circles. An ordered list uses the ol element and numbers the items as 1, 2, 3 and so on.
The doctor appointment example keeps its earlier rows and adds pricing in the footnote area. The footnote highlights the fee package, and an unordered list follows it, with one li element for each fee package.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Doctor's Visit Appointments</title>
<style>
table {
border: 2px solid black;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: lightblue;
color: white;
}
tr:nth-child(odd) {
background-color: lightyellow;
}
</style>
</head>
<body>
<h1>Doctor's Visit Appointments</h1>
<table>
<caption>List of upcoming appointments</caption>
<thead>
<tr>
<th>Patient Name</th>
<th>Date</th>
<th>Time</th>
<th>Doctor</th>
<th>Reason for Visit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adil</td>
<td>2024-05-10</td>
<td>10:00 AM</td>
<td>Dr. Shams</td>
<td>Follow-up</td>
</tr>
The closing part adds the second patient row, closes the body of the table and writes the footnote inside tfoot across all five columns. A line break separates the words Fee Packages from the list marker to make the footnote easier to read.
<tr>
<td>Zaki</td>.
<td>2024-05-15</td>
<td>2:00 PM</td>
<td>Dr. Qamar</td>
<td>Check-up</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
* This table displays a sample list of appointments. <br>
**Fee Packages:
<ul>
<li>Standard Consultation: Rs.500</li>
<li>Follow-up Visit: Rs.300</li>
<li>Comprehensive Check-up: Rs.1,000</li>
</ul>
</td>
</tr>
</tfoot>
</table>
</body>
</html>
The rendered page keeps the appointment table and shows the three fee packages as bullets under the footnote.
The next example uses a JavaScript array to create a shopping list whose items appear as bullets.
The shoppingItems array holds Milk, Bread, Eggs and Apples. An empty ul element holds the bullets, and the updateList method builds one li element for each array entry, so any change to the array appears in the list.
<IDOCTYPE html>
<head>
<title>Shopping List</title>
</head>
<body>
<h1>My Shopping List</h1>
<ul id="shoppingList"></ul>
<script>
const shoppingItems = ["Milk", "Bread", "Eggs", "Apples"];
function addItem() {
const newItem = document.getElementById("newItemInput").value;
shoppingItems.push(newItem);
updateList();
}
function updateList() {
const listElement = document.getElementById("shoppingList");
listElement.innerHTML = "";
for (let i = 0; i < shoppingItems.length; i++) {
const item = shoppingItems[i];
const listItem = document.createElement("li");
listItem.textContent = item;
listElement.appendChild(listItem);
}
}
updateList();
</script>
<br>
<input type="text" id="newItemInput" placeholder="Enter new item">
<button onclick="addItem()">Add Item</button>
</body>
</html>
The page shows the heading My Shopping List, the bullet list, a box for new items and an Add Item button. Clicking the button adds the typed text to shoppingItems through addItem and then calls updateList so the new item appears as a bullet.
A function is a block of code used repeatedly for one operation. It is defined once and called many times, which simplifies code and reduces the number of lines.
The definition uses the function keyword followed by the function name and parentheses for any input parameters. The code of the function sits inside curly brackets. In this example updateList first clears what is already shown, then moves through shoppingItems in turn, converts each item to a bullet point and appends it to the list on the page.
evenNumbers = [2, 4, 6, 8, 10];
combinedArray = oddNumbers.concat(evenNumbers);
oddNumbers.slice(2, 4);