Conventional websites are static since they are only made with HTML and CSS. Every time a user visits the website, the same content is displayed. This configuration is sufficient for basic informative webpages; however, JavaScript is used to provide further interaction. Few reasons that sophisticated programming concepts is crucial when using JavaScript to create dynamic webpages are as follows:
Interactivity
User input such as clicks, scrolling, and form submissions are not supported by basic HTML. Writing code that responds to these events is made possible by JavaScript, which enhances the user interaction on the website. When a button changes color or a form verifies your data before submitting, such functionalities which manage user interaction are examples of JavaScript enhancement.
DATA HANDLING
Diagram image pending upload by Admin.
Data Handling
In order to show information about products or user comments, for example, websites frequently need to interact with data. Functions & loops are examples of ideas that help manage and change this data. For instance, you might use functions to carry out computations depending on user input or a loop to list things from a database and plot them in the form a graph.
Dynamic Content Updates
In the absence of JavaScript, modifying the content of a website requires a page refresh. Updates to some sections of the website may be made without a page reload using JavaScript, which enhance user involvement and performance. For example a newsfeed that updates itself with new content without requiring you to click on a "refresh" button. This way, manual clicks are minimized for newer content updation.
Complex User Interfaces
Drop- down menus, picture slideshows, live chat and other such components are common on modern websites. This can only be accomplished via manipulating the webpage structure, using JavaScript. However at times, if the focus resides more on incorporating more and more features rather than the layout and navigation; it can result in redundancy. Hence, a complex user interface may arise as shown in Fig. 26, where every option is accessible from main menu as well as side menu.
Diagram image pending upload by Admin.
Diagram image pending upload by Admin.
JavaScript arrays are a good way for organizing sets of similar data as they allow storing numerous values in a single container. For instance:
Let's say to store names of fruits, distinct variables for every fruit type will look like:
"apple" be fruit1, "banana" be fruit2, "orange" be fruit3, etc.
Alternatively, you may keep every fruit in a single variable by using an array. Creating an array will look like this:
A JavaScript array's index is used to access each element and starts at 0. This indicates that the index of the first element is 0, the index of the second element is 1, and so on. As stated above, our array is named 'fruits' and contains the words "apple", "banana" and "orange". Every object has an index number where the object is placed in the array. First, "apple" is placed at index 0, followed by "banana" at index 1, then "orange" at index 2. In JavaScript, an array can store various types of data, such as alphabets, numbers or a combination of both.
To traverse elements of an array and if same operation needs to be applied on several components, loops are used. To demonstrate the use of loop that iterates through every item in the 'fruits' array and outputs the result to the console is as follows:
1. for (let i = 0; i < fruits.length; i++)
2. {
3. console.log(fruits[i]);
4. }
Key points about arrays;
You may use 'push()' to add more items to the end and 'pop()' to remove items from the end.
Use 'length()' to find out how many items are in the array.
To go through every thing in the array, you can use a 'for- loop'.
JavaScript arrays are flexible in a sense that they can expand or contract to accommodate additions or deletions of items. JavaScript does not require that every element in an array be of the same type, as compared to several other programming languages. Hence, different types of data can be combined in a single array. Arrays are a good tool to manage groups of data in JavaScript code.
Let us start with a simple program to calculate the sum of first 10 positive integers using a for- loop on line 13 as show in Fig.27. Thereafter, it stores the integers in an array using push() function, on line 15 and later prints these numbers and the sum; as can be seen in Fig.28.
1 <IDOCTYPE html>
2 <html>
3 <head>
4 <title>Sum of First 10 Integers</title>
5 </head>
6 <body>
7
8 <script>
9 function calculateSum() {
10 let sum = 0;
11 let numbers = [];
12
13 for (let i = 10; i <= 10; i++) {
14 sum += i;
15 numbers.push(i);
16
In JavaScript, you can move around an object's structure by using the dot operator (.) for obtaining the parameters and methods of the object. Either to get the value of a property from an object (use the dot operator and then the name of the property) or to call a function.
17 document.getElementById("sumDisplay").textContent = "The sum of the first 10 integers is: " + sum; 19 20 let output = "The first 10 integers are: ["; 21 for (let i = 0; i < numbers.length; i++) { 22 output += numbers[i]; 23 if (i < numbers.length - 1) { 24 output += ", "; 25 } 26 } 27 output += "]; 28 document.getElementById("numberDisplay").textContent = output; 29 } 30 </script> 31 32 <button onclick="calculateSum()">Calculate Sum</button> 33 <br> 34 <p id="numberDisplay"></p> 35 <p id="sumDisplay"></p> 36 37 </body> 38 </html>
On line 9, we define a function namely 'calculateSum()', in which a for- loop is executed starting from 1 till 10. On line 14, a variable 'sum' which has initial value of zero, is added with the index 'i'. This way, by the line the loop terminates, we will be having the sum of all the ten numbers, stored in variable 'sum'. Noteable point is the next line where the index is stored in the array using push() function, which will always append (add to the existing) array value of '1'.
Diagram image pending upload by Admin.
the sum of all the ten numbers, stored in variable 'sum'. Noteable point is the next line where the index is stored in the array using push() function, which will always append (add to the existing) array value of '1'.
Activity-3
Change the code of Fig.27 for the following output:
1 <IDOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>Shopping List</title> 5 <style> 6 table { 7 border- collapse: collapse; 8 width: 100%; 9 } 10 th, td { 11 padding: 10px; 12 border: 1px solid Lightgray; 13 text- align: left; 14 } 15 </style> 16 </head> 17 <body> 18 <h1>My Shopping List</h1> 19 <input type="text" id="newItem" placeholder="Enter item name"> 20 <button onclick="addItem()">Add Item</button> 21 <br> 22 <table id="shoppingListTable"></table> 23 24 <script> 25 let shoppingList = []; 26 27 function addItem() { 28 const newItemName = document.getElementById ("newItem").value; 29 30 if (newItemName != "") { 31 shoppingList.push(newItemName); 32 33 document.getElementById("newItem").value = ""; 34 35 updateShoppingListTable(); 36 } else { 37 alert("Please enter an item name!"); 38 } 39 } 40 41 function updateShoppingListTable() { 42 const table = document.getElementById ("shoppingListTable");
Diagram image pending upload by Admin.43 44 table.innerHTML = ""; 45 46 const headerRow = document.createElement("tr"); 47 const headerItem = document.createElement("th"); 48 headerItem.textContent = "Shopping List Items"; 49 headerRow.appendChild(headerItem); 50 table.appendChild(headerRow); 51 52 for (let i = 0; i < shoppingList.length; i++) { 53 const itemRow = document.createElement("tr"); 54 const itemCell = document.createElement("td"); 55 itemCell.textContent = shoppingList[i]; 56 itemRow.appendChild(itemCell); 57 table.appendChild(itemRow); 58 } 59 } 60 </script> 61 </body> 62 </html>
The next code of Fig.29 shows how to use a JavaScript array to handle a shopping list. The array keeps track of the item names and the functions in the code handling of adding new items and updating the list on the webpage automatically.
The webpage has a heading, an add- item button, a text box where you may write the products and a table that shows your shopping list.
We maintain the list using JavaScript, as:
The items are being added in an array we call "shoppingList".
The "addItem()" function is activated upon clicking the "Add Item" button which checks to see if the box has entered text that is then added to the "shoppingList" and the box is cleared to be rewritten.
1 After that the new item is then shown in the table by using a different function called "updateShoppingListTable()". 2 Additionally, a top row labeled "Shopping List Items" also is visible. 3 Lastly, it adds each item to a new row in the table by going through the "shoppingList" one by one. In this manner, any chosen item to be purchased is added to the table.
The respective output is shown in Fig.30.
The major functions associated with arrays in JavaScript are:
Push() function adds the value at the end of the array. In the following code, initially an array is created and later another value is inserted using the push() function that appends at the end.
Code:
Output:
Initial array: 1,3,5,7,9
After push(11): 1,3,5,7,9,11
IndexOf() function searches for and locates the given element in an array. If present, it returns the index number where the said element resides. For instance: