User Tools

Site Tools


en:web_development:lists:javascript

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
en:web_development:lists:javascript [2021/12/01 16:10]
mag
en:web_development:lists:javascript [2023/08/16 09:33] (current)
Line 1: Line 1:
-====== Web Development Lesson - Lists ======+====== Web Development Lesson - Lists ======
 ===== Javascript Lists ===== ===== Javascript Lists =====
 +==== Objectives ====
 +In this exercise you will use an array to store a list of items, use a for loop to repeat a block of code, and use an if statement to run different instructions based on user input.
 ==== Setup ==== ==== Setup ====
-  * We'll use the first file you created in this lesson called 'lists.html', so open that file in Visual Studio Code.+  * We'll use the first file you created in this lesson called '[[https://techschool.murraygunn.id.au/webdev/classes/lists/3/lists.html|lists.html]]', so open that file in Visual Studio Code.
   * Create a file called 'lists.js' in the same directory.   * Create a file called 'lists.js' in the same directory.
   * We'll also return to [[https://jsfiddle.net|jsfiddle]] to try out a few things.   * We'll also return to [[https://jsfiddle.net|jsfiddle]] to try out a few things.
   * We'll start with a blank slate for this, so if you have anything in the HTML, CSS or Javascript panels of jsfiddle, delete them.   * We'll start with a blank slate for this, so if you have anything in the HTML, CSS or Javascript panels of jsfiddle, delete them.
 +
 +==== External Scripts ====
 +  * We'll start in Visual Studio Code.
 +  * Just as we created an entry in <html><head></html> to link to the external style sheet, we need to tell the browser where to find our javascript code.
 +  * Create a new line in <html><head></html> and type 'script', then select 'script:src'.
 +  * Type the name of our javascript file 'lists.js' into the <html> src </html> attribute.
 +<code><script src="lists.js"></script></code>
 +  * We can now work in our javascript file and the browser will find it when we open the 'lists.html' page.
  
 ==== Arrays ==== ==== Arrays ====
-  * This will be easier to see in [[https://jsfiddle.net|jsfiddle]] so open that page. +  * An 'array' is essentially a list in code form. 
-  * An 'array' is essentially a list in code form, and it looks like thisCopy this code into the Javascript panel of jsfiddle+  * Type the following text into 'lists.js'
-<code>cars = ['Ferrari', 'Porsche', 'Lamborghini'];</code> +<code>players = ['David Ospina Ramirez', 
-  * By now you should be familiar with the form of the statement. <html>cars</html> is the name of a variable and it now holds everything after the <html> = </html> sign. +           'Johan Andres Mojica Palacio', 
-  * <html> [] </html> identifies an array, in this case holding a list of cars.+           'Gustavo Leonardo Cuellar Gallego', 
 +           'Duvan Esteban Zapata Banguera'];</code> 
 +  * By now you should be familiar with the form of the statement. <html>player</html> is the name of a variable and it now holds everything after the <html> = </html> sign. 
 +  * <html> [] </html> identifies an array, in this case holding a list of players.
   * Each of the player names is text, so we surround them with <html> ' </html> signs.   * Each of the player names is text, so we surround them with <html> ' </html> signs.
-  * I've included names of 3 cars, but there are many more. Feel free to add any others you like using the same format. +  * I've included names of 4 Colombian football players, but there are many more. Feel free to add any others you know using the same format. 
-  * To be able to display these items, we need to be able to reference them. +  * I've written each of the names on a separate line to make it clear. This is good practice, but it's not essential - you can string them all on the same line as long as you separate the items with a <html> , </html>
-  * You've seen how to do this before. In the previous lesson, we accessed elements with specific tags using <html>document.getElementsByTagName('span')[2]</html>. <html>document.getElementsByTagName</html> is a list of all elements with the tag 'span'. <html>[2]</html> means that we access the 3rd item. Remember that the first is <html>[0]</html>+ 
-  * We now need to take each of the names in this array and print them on the screen as a list. For this we'll use a 'for loop', but before we try that on this listlet'take a look at how 'for loopswork.+==== Referencing Array Elements ==== 
 +  * To display these items, we need to be able to reference them. 
 +  * You've seen how to do this before. In the previous lesson, we accessed elements with specific tags using <html>document.getElementsByTagName('span')[2]</html>. <html>document.getElementsByTagName('span')</html> is an array (a listof all elements with the tag <html>span</html>. <html> [2] </html> means that we access the 3rd item in the list. Remember that the first item is <html> [0] </html>
 +  * We can see this more easily in jsfiddle. 
 +  * Create a simple array in the Javascript panel as follows. 
 +<code>cars = ['Ferrari', 'Porsche', 'Lamborghini'];</code> 
 +  * Here, the array is simple enough that I've left it on single line. 
 +  * Now, let's display the first element in the list on our page. 
 +<code>document.body.innerHTML = cars[0];</code> 
 +  * Run the code and see that it displays 'ferrari', the first item. 
 +  * Try changing the number inside the <html> [] </html> and check the results to be sure you understand how it works. 
 +  * Using this technique, we can display the results of our list in our Visual Studio page. 
 +  * Open 'lists.html' and add an unordered list just before the closing <html></body></html> tag. 
 +<code>  <h2>Players</h2> 
 +  <ol></ol> 
 +</body></code> 
 +  * We'll use this to display our Javascript array. 
 +  * After the players list in 'lists.js', add the following code to generate our list code. 
 +<code>playerList = ""; 
 +playerList += "<li>" + players[0] + "</li>"; 
 +playerList += "<li>" + players[1] + "</li>"; 
 +playerList += "<li>" + players[2] + "</li>"; 
 +playerList += "<li>" + players[3] + "</li>";</code> 
 +  * Can you see how this works? We're building string with all our list items, one on each line. Each has the opening and closing list ags with the list item in between. 
 +  * Next we need to display the string we've created. 
 +<code>document.getElementsByTagName('ol')[2].innerHTML = playerList;</code> 
 +  * This looks for the 3rd <html><ol></html> tag and inserts the list string there. 
 +  * If you run the code nowit probably won't work because the Javascript code executes before the HTML code has finished loading (ie the 3rd <html><ol></html> tag doesn't exist when the code runs). To avoid this, we need to wrap the display command inside a function that only runs when the page is fully loaded. 
 +<code>window.onload = function() { 
 +  document.getElementsByTagName('ol')[2].innerHTML = playerList; 
 +}</code> 
 +  * <html>window</html>, like <html>document</html> identifies the whole page. 
 +  * <html> .onload </html> triggers when the HTML code has finished loading. 
 +  * When this is truethe browser will run the <html>function</html> containing all the code between <html> {} </html>
 +  * You don't need to remember or understand all this completely, but you should be able to recognise this pattern and be able to apply it when necessary. We'll use it often during the course so you become familiar with it. 
 +  * The code should work now when you run it, but if you've added all 16 players, listing them all would take more work. And some lists (like the list of products on MercadoLibre) have thousands of entries. 
 +  * We can save ourselves a lot of time by writing a 'for loopthat will run through all entries and create the string dynamically.
  
 ==== For Loops ==== ==== For Loops ====
 +  * The name ‘for loop’ will seem strange if you’re new to programming. It essentially means that ‘for’ each item in the list, we will ‘loop’ through a given block of code. ie. we’re going to apply the same code (add the item to our string) to every player.
 +  * Let’s go back to jsfiddle to see how this works.
   * Type the following code into the Javascript section below the cars array.   * Type the following code into the Javascript section below the cars array.
 <code>for (i = 0; i < 10; i++) { <code>for (i = 0; i < 10; i++) {
Line 27: Line 78:
   * For each of these, by convention, we'll use a variable <html> i </html>, short for 'iterator'.   * For each of these, by convention, we'll use a variable <html> i </html>, short for 'iterator'.
   * <html>i = 0</html> means that the first time we run the code, the variable <html> i </html> will have a value of zero.   * <html>i = 0</html> means that the first time we run the code, the variable <html> i </html> will have a value of zero.
-  * We'll run the code as long as <html>i < 10</html>.+  * We'll run the code as long as <html>i < 10</html> is true.
   * Finally, <html>i++</html> is the same as <html>i = i + 1</html> so each time we loop through the code, we'll increment the variable <html> i </html>. So it will run with a value of i incrementing from 0 to 9.   * Finally, <html>i++</html> is the same as <html>i = i + 1</html> so each time we loop through the code, we'll increment the variable <html> i </html>. So it will run with a value of i incrementing from 0 to 9.
   * Let's see this in action by adding an 'alert' to display the value of <html> i </html>.   * Let's see this in action by adding an 'alert' to display the value of <html> i </html>.
Line 52: Line 103:
 ==== Iterating Arrays ==== ==== Iterating Arrays ====
   * So now that you understand how for loops work, we can apply it to an array.   * So now that you understand how for loops work, we can apply it to an array.
 +  * Open your jsfiddle tab again.
   * Let's edit the for loop you have already.   * Let's edit the for loop you have already.
 <code>var text = ""; <code>var text = "";
 for (i = 0; i < 10; i++) { for (i = 0; i < 10; i++) {
- text += i + "<br />";+ text += cars[i+ "<br />";
 } }
 document.body.innerHTML = text;</code> document.body.innerHTML = text;</code>
Line 61: Line 113:
 <code>var carList = ""; <code>var carList = "";
 for (i = 0; i < 10; i++) { for (i = 0; i < 10; i++) {
- carList += i + "<br />";+ carList += cars[i+ "<br />";
 } }
 document.body.innerHTML = carList;</code> document.body.innerHTML = carList;</code>
-  * In the for loop, the starting condition <html> i = 0 </html> and iterating statement <html> i++ </html> are still valid, but we need to adjust the continuing condition+  * In the for loop, the starting condition <html> i = 0 </html> and iterating statement <html> i++ </html> are still valid, but we need to adjust the continuing condition to stop at items.
-  * I only have cars in my list, so I could write <html> i < 3 </html>, but you may have added more cars to your list. You could change the number directly to match your list, but in the future you'll have lists pulled from databases and you won't always know exactly how many elements are in the list. +
-  * You can discover the number of elements using <html> .length </html>, so let's change the for loop to the following.+
 <code>var carList = ""; <code>var carList = "";
-for (i = 0; i < cars.length; i++) { +for (i = 0; i < 3; i++) { 
- carList += i + "<br />";+  carList += cars[i+ "<br />";
 } }
 document.body.innerHTML = carList;</code> document.body.innerHTML = carList;</code>
-  * Run it now and see that it shows exactly as many elements as you have in your list. +  * If you run his nowit should show all 3 cars, one on each line
-  * We can then change the display code to show the list item tag and the car name corresponding to the current value of <html> i </html>+  * Now have a go at applying this yourself to the list of players in Visual Studio Code. 
-<code> var carList = ""; +  * Here's my version.
-for (i = 0; i < cars.length; i++) { +
- carList += cars[i] + "<br>"; +
-+
-document.body.innerHTML = carList;</code> +
-  * Finallywe need to display the items as an HTML list+
-  * Update the string as follows. +
-<code>carList += "<li>" + cars[i] + "</li><br>";</code> +
-  * Notice that we're missing the type of list. Let's add an unordered list to the HTML document. +
-<code><ul> +
- +
-</ul></code> +
-  * Then we update the display statement to refer to our <html><ul></html> tag. +
-<code>document.getElementsByTagName('ul')[0].innerHTML = carList;</code> +
-  * Run your code to see the bulleted list of cars. +
- +
-==== External Scripts ==== +
-  * Let's see how this all works on a real site using Visual Studio Code. +
-  * Just as we created an entry in <html><head></html> to link to the external style sheet, we need to tell the browser where to find our javascript code. +
-  * Create a new line in <html><head></html> and type 'script', then select 'script:src'+
-  * Type the name of our javascript file 'lists.js' into the <html> src </html> attribute. +
-<code><script src="lists.js"></script></code> +
-  * We can now work in our javascript file and the browser will find it when we open the 'lists.html' page. +
- +
-==== Arrays ==== +
-  * An 'array' is essentially a list in code form. +
-  * Type the following text into 'lists.js'.+
 <code>players = ['David Ospina Ramirez', <code>players = ['David Ospina Ramirez',
            'Johan Andres Mojica Palacio',            'Johan Andres Mojica Palacio',
            'Gustavo Leonardo Cuellar Gallego',            'Gustavo Leonardo Cuellar Gallego',
-           'Duvan Esteban Zapata Banguera'];</code> +           'Duvan Esteban Zapata Banguera']; 
-  * By now you should be familiar with the form of the statement. <html>player</html> is the name of a variable and it now holds everything after the <html> = </html> sign+ 
-  * <html> [] </html> identifies an arrayin this case holding a list of players+window.onload = function () { 
-  * Each of the player names is textso we surround them with <html> </html> signs+  playerList = ""; 
-  * I've included names of 4 Colombian football playersbut there are many more. Feel free to add any others you know using the same format+  for (i = 0; i < 4; i++) { 
-  * I've written each of the names on separate line to make it clearThis is good practice, but it's not essential - you can string them all on the same line as long as you separate the items with a <html> </html>+    playerList += "<li>" + players[i] + "</li>"; 
-  * We now need to take the names in this array and print them on the screen as a listFor this we'll use a 'for loop', but before we try that on this list, let's take a look at how 'for loopswork.+  } 
 +  document.getElementsByTagName('ol')[2].innerHTML = playerList; 
 +}</code> 
 +  * Did you have something similar? 
 +  * If you added more players, you won'be using the number 4. Or if you did, you won't see the whole list. 
 +  * In fact, if you pull a list from a database, which we'll do much later in the course, you likely won't know how many items are in the ilst. What do you do then? 
 +  * Thankfully, Javascript can count the number items in an array for you using <html> .length </html>
 +  * Let's see how this works in jsfiddle. 
 +  * Add an alert to your Javascript code. 
 +<code>alert("cars has " + cars.length + " items.");</code> 
 +  * Run that and check that it does what you think it should. 
 +  * So we can change our continuing condition for the list of players as follows. 
 +<code>for(i = 0; i < players.length; i++) {</code> 
 +  * Run it now and see that it shows exactly as many players as you have in your list. 
 +  * Congratulations on creating a list using Javascript. 
 + 
 +==== Conditional Statements ==== 
 +  * Sometimes the action you take will depend on some other factor - user input, previous actions or information from a database for example. 
 +  * The simplest of these is the 'if statement'
 +  * Let's jump back to jsfiddle to see how this works. Delete all the Javascript you have there at the moment. 
 +  * Enter the following code into the Javascript panel. 
 +<code>var x 2; 
 +if (x == 2) { 
 + alert 'the condition is true'; 
 +}</code> 
 +  * The basic structure of this code is <html>if (condition) { code to execute if true }</html>
 +  * We have a condition inside the <html> () </html>, and only if that condition is true do we run the code inside <html> {} </html>
 +  * In this case, our condition is <html> x == 2 </html>, which checks the value of <html> x </html> and the value of <html> 2 </html>. If the value of <html> x </html> is 2, then it will run the code displaying an alert
 +  * Since we've just defined <html> x = 2 </html> (first line), this condition is true and the alert will be displayed. Try it now. 
 +  * Now change the value of <html> x </html> to 5 (or anything but 2) and run the code again. 
 +  * Nothing is displayed. Let's add a message if it fails too. 
 +<code>var x = 2; 
 +if (x == 2) { 
 + alert 'the condition is true'; 
 +} else { 
 + alert 'the condition is false'; 
 +}</code> 
 +  * Here, we have added <html>else</html> with code that will run if the condition is not met. Run the code again with the wrong value of <html> </html> and see the new statement
 +  * Nowlet's apply that to our checklist in 'lists.html' using Visual Studio Code
 +  * If the user checks checkbox, we will make the associated text greyIf they uncheck it, we'll make the text black again. 
 +  * Add an attribute to each of the list items to call Javascript function. 
 +<code>        <li><input type="checkbox" name="flour" onchange="toggleCheckbox('flour')">100g flour</li> 
 +        <li><input type="checkbox" name="eggs" onchange="toggleCheckbox('eggs')">2 eggs</li> 
 +        <li><input type="checkbox" name="milk" onchange="toggleCheckbox('milk')">300ml milk</li></code> 
 +  * <html>onchange=""</html> will trigger whenever there is a change to the element - in this case when the checkbox is checked or unchecked. When triggered it will run the Javascript code between the <html>""</html>
 +  * We will call our Javascript function 'toggleCheckbox' and pass the function the name of the checkbox element so the function will know which line to update. 
 +  * Now, save 'lists.html' and open 'lists.js'
 +  * Add our function below the existing code. 
 +<code>function toggleCheckbox(item) { 
 +}</code> 
 +  * First we define the code as a 'function' using <html>function</html> which means it will only run when specifically calledIn this case we'll call it by clicking the checkbox, but it could also be called from other code. 
 +  * Next, we name the function 'toggleCheckbox'
 +  * Then we assign the information passed by the <html>onChange</html> attribute (the name of the checkbox) to the variable called <html>item</html>
 +  * Finally, we have <html> {} </html> ready to contain our code to be run. 
 +  * To make things a bit easier, we'll find the actual checkbox using the name, and assign that to a variable. Copy the following code inside the <html> {} </html>
 +<code>  cb = document.getElementsByName(item)[0];</code> 
 +  * We've called our checkbox 'cb'
 +  * This time we're finding our element by name instead of tag so we use <html>.getElementsByName</html>. Then we choose the first in the list (<html>[0]</html>). 
 +  * Now we can add our condition. 
 +<code>  if (cb.checked) { 
 +  } else { 
 +  }</code> 
 +  * If our checkbox 'cb' is checkedthen we'll run some code to make the text grey, otherwise we'll run code to make it black. 
 +  * The text isn't part of our checkbox, so we need to find the element it belongs to, which in this case is the parent element (our <html><input></html> element is directly inside our <html><li></html> element) so we use <html>.parentElement</html>
 +  * The full code is then as follows. 
 +<code>function toggleCheckbox (item) { 
 +    cb = document.getElementsByName(item)[0]; 
 +    if (cb.checked) { 
 +        cb.parentElement.style.color = "gray"; 
 +    } else { 
 +        cb.parentElement.style.color = "black"; 
 +    } 
 +}</code> 
 +  * Run that and try it out for yourself. 
 + 
 +==== Final Code ==== 
 +  * [[https://jsfiddle.net/maganthro/t3bq247f/13/|jsfiddle]] 
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/es.php|lists.html]] 
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/listsjs.php|lists.js]] 
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/lists.html|final result]]
  
 +[[en:web_development:lists:exercise|Next: Exercises]]
en/web_development/lists/javascript.1638403811.txt.gz · Last modified: 2023/08/16 09:33 (external edit)