Loading
Lesson 07
Courses / Full Stack Web Dev Bootcamp (August 26 - September 26, 2024)
Intro to JavaScript - Bootcamp Day 7 (2024-09-05)

Learn how to use the JavaScript programming language to manipulate an HTML document.

You learn how to change CSS properties of an HTML element using JavaScript.

You learn different ways of finding an HTML element, like by id or class name. You also learn to use querySelector function.

You learn about JavaScript variables and arrays.

You learn how to build a simple image gallery with images changing pressing a next button.

Video Transcript

Today, we'll talk about JavaScript, the programming language for the web, and you're going to need a search code from the repository here, for Stack Web Dev 3, from the owner and BKTec world. So why JavaScript? So basically, in the beginning, we had HTML, CSS, so we would have documents, and we can make them pretty, however, that's not so highly interactive, like you don't have things changing dynamically, like real-time stuff going on, like social media today. And then to do that, we have to actually manipulate the document in real-time. That is, we change the HTML structure as we go about interacting with the website via clicking stuff, commenting on something, interacting in any kind of ways. And for that, we need the JavaScript programming language that's now built into any browser today. So what you can do is, if you want to do some JavaScript, you can actually open the developer tools, type up 12, I'm in Firefox right now, but it's the same thing in Chrome and any other browser. I go to the console tab, you can trash or click the icon to circle with the dash, cross circle, and to clear the console, and here you can start doing JavaScript. So basically a programming language, you can do stuff as simple as mathematical operations like two plus three, and it will give you back five. And you can do all the other stuff, seven minus three, seven times three, when you want, let's say six divided by two. And even the remainder, if you do what's six divided by three, what's the remainder of that division? That's zero. That's the module operator there. Okay. So that's the most basic thing, JavaScript. Anybody can do JavaScript just by doing math. So now that you've already certified yourself as JavaScript master, let's keep going. Anyway, we're going to go here to VS code, where I have my source, my project, this boot camp. And if you recall, there's a folder SRC that has CSS and HTML files. So the index is this one. I opened the live preview, by the way, control shift P, I choose live preview show preview internal browser from the live preview extension and visual studio code. So I can see it on the side. So I can click to read the news to go to the news.html. Now I'm going to teach you how to do the following. Like, for example, I have this paragraph here, which is line 11, how can we manipulate that with JavaScript? For the sake of example, let's say I want to highlight this with the kind of yellowish background. How would I do that? Just using JavaScript. Of course, you can do CSS and put a selector for this person here and then write in the CSS file, but I want to demonstrate your JavaScript. So to write some JavaScript code, what we do is I'll show you a different way. So the most straightforward way is you want to create a script tag here right before the end of the body. And then between the script, open and close tag, you're going to write JavaScript code. And first thing you got to do in JavaScript is you got to find what you want to manipulate in the document, in the HTML structure. In this case, it's this paragraph, but there's a problem. How can I uniquely find this? It's the same thing as CSS, right? We need a selector. And there could be many paragraphs in the page. How can I go about selecting only this one? There are multiple ways to do that. The simplest way, like I told you for CSS, is just by adding an ID. So we can add an ID there. Let's say section title, something like that. Now that I have an ID that uniquely identifies that, I can actually target that with JavaScript. So I have to write here programming language constructs. Let me restart because I don't want that thing out of completing. There you go. So in JavaScript, you need a way to interface with the document. And that's through the document interface, which has an object called document. And I said the word object. So in JavaScript, there are many ways of structuring the data. One of them is through an object. You can think of that as like in the real world, an object has attributes. And it has stuff it can do. For example, a car is an object that has color, has a make, and all these other attributes. However, it also has some things it can do, like drive, enable the windshield wipers, turn the lights on, et cetera. So if you want to access something that belongs to an object, we use the dot notation. So in this case, I want to ask the document to do something for me. So I have to say dot there. Now, the right-hand side is the operation of what I want to do. We should call these functions, which is a set of instructions to do for the computer to do. And the one I want to use is getElementById. That's the name of the function. Now, this function got to type exactly like I did with the lowercase g, e, t. And then every other word has the first letter capitalized. That's called the camel case naming convention. OK, it's important that every character is important, the casing, whether it's upper or lower. And then when we get functions of instructions for something to be done, they have to define somewhere. And that somewhere has kind of like a blueprint of all the instructions, like a recipe. However, somebody has to actually call for that to happen. So they have to call the function so all these statements are executed. So to do that, we use the notation with parentheses like this, open and close parentheses. Some functions or instructions, they rely on extra information to do their job. In this case, we're asking a document to find on the document an element by a specific ID. However, you need to tell it what is the ID of the thing you're looking for. That's why you've got to type between the parentheses what we call the argument, some input to the function. In this case, I have to match exactly what I typed for the ID of the paragraph in line 11. So I would do that within quotes. It could be single or double, it doesn't matter in this situation. So I'm going to use single quotes there because I like writing that way. But you can use double as well. OK, so when you do this, it will call this function and some set of instructions will be run to search the document. And it's going to pretty much go, OK, that's not the one. And it hits this line here, 11. And it's going to see, oh, the ID matches the thing I'm looking for. Therefore, a reference to this element here that represents this paragraph will be given back to whoever called the function. So you can think of visually, you can imagine this paragraph will be replaced here because it's been found. OK, and then from that, we can do other stuff like changing the style of that paragraph kind of object, if you think it that way. And you can do the same thing as we did before, you can put a dot because I want to access the attributes of that object. And I put style because I want to access the style attributes. And from that, I can change the background color, which is a name pretty much almost the same as CSS except the naming convention. Instead of using dashes to separate the word, all you do is combine the words together with the first letter of each subsequent word capitalized. So instead of saying background dash color, I'm going to say background capital C color. OK, and if I just write it like this, this is actually going to give me the background color of that paragraph, which is I think it's on set right now, right? Something like transparent or white. Then I want to change that to a highlight color, which is yellow. So to change anything, we're going to use the equal sign like this. Now, you don't need to have space before and after as just optional for readability. Now, this equal sign is not comparison. OK, you might know from math equality, like usually people think about comparing one thing to another. In this case, it's assignment or attribution of something. A value on the right hand side will be replacing whatever is on the left hand side, in that case, the new background color. And I want that to be yellow, except I must type that with quotes because if I don't have quotes, that thing will be interpreted by the programming language as something special. And usually it's like a variable or a reserve keyword like document, as we'll see, I'll understand later on. And when you have quotes surrounding characters, this is a general term, a concept of programming languages. It's called a string. A string is a sequence of characters, and usually they always come surrounded by quotes. In this case, it could be single or double or even back tick. Now, you notice on the right hand side, it immediately turned yellow. And that's because it does it so fast that you didn't even notice that the document's manipulated. And to demonstrate that it's actually not the original document state, I'm going to put a delay here. You don't have to notice. Just put a delay here to only change that color after two seconds. So let me put that. See, after two seconds, it turns yellow. So what's happening is the browser will receive the HTML file, the CSS, and the other stuff. So basically, it parses through the HTML code, and then it renders everything as you saw before, and then it reaches the script, and it loads that script and executes the code from the top to the bottom. So this code is just telling me, execute the following after two seconds. It's 2000 because it's in milliseconds, so you got to divide by 1000 to get seconds. And after two seconds, it executes this line, which will find the element whose idea section title and go to its style properties and change the background color to a new value right hand side that is yellow. So that's why what you see there. OK, that's pretty much how we do in JavaScript. We find a way to find the element, and then we manipulate that, change its properties. Now let me teach you how we can do that on click, because it's very common that we click something in the web page and something else happens. So how do we do that? Let me see what I can do here. Let's say, let me do the following. I want to be able, when I click this image, I want to add a border surrounding it. I don't know why I want to do it, it's just for example. How would I do that? Well, OK, the event here is click. So these are called events. So pretty much when you go to a website, you can click something, you can highlight something, you can move your pointer over an element. Those are all called events that you can capture through the JavaScript commands. So I'm going to go to the image. This is the one that's making that image. I'm going to add an attribute. Remember, attributes find the open tag, right hand side with a space. This attribute is going to be called on click and equal sign and some value here. Now the value here has to be a set of instructions that you have to define for what you want to happen when you click the image. These instructions are encapsulated in what we call a function. So you have to define your own function. Now let's say I want to call that add border like this. And that would be the function that I'll make in the JavaScript code. Now to make that function actually be called or the instruction executed, I need the parentheses like that. OK, now that we got that, we're going to scroll down and define that function in between the script types here. It could be before or after this. It doesn't really matter. So I'm going to add function keyword. That's how you define a function, space and its name. Its name will be matching whatever we type for the on click, which is add border. Notice I use the camel case convention again. That's what we usually do in JavaScript. Other programming languages might be a word separated by underscore or dash like we did in CSS. OK, we need parentheses to specify the inputs to this function. Right now we don't care about anything being given additionally, so it doesn't need to know anything. So I'm going to leave it empty. Now to define the statements that will be called or executed for this function, you put the curly brace like this and you break a line and write the statements between the open and close. People usually like to add a space here, but it's just for readability. And I press tab to add the indentation. Remember, usually when we open something like open HTML tag, open a curly brace, we add indentation. That's why VSCode here usually will add all those spaces. It's usually two for each level. So you can see there's this one here for one level, this one. And this one here is for the script tag that was open. And this one here is for the curly brace. And every time we close it, we go back to one level to the left. Anyway, so how can we change that element to add a border? Well, first we got to find that. We got to select that element. How can we do that? Well, let's look at the definition in the HTML. I see we got source, got with, alt. But we don't have no way to do by ID. So that's one way you can do it. Since I already taught you that, let me teach you another way. So I'm going to do it via class. OK, class. I'm going to add a class there. Let's call it pet image about that. And since I'm not doing CSS for this, I just want to use the class for JavaScript. People like adding the prefix js-. So this class is not really used for stars, more for capturing this with JavaScript. So this is like a very traditional thing. Anyway, how do we ask the document for that element that has this specific class? Well, you can do type document, and you're going to follow kind of the same pattern, dot, and then you're going to go get. And if you have Visual Studio Code, you'll probably get these auto-completion things, which are very nice if you don't know exactly what you have to use. And you see there's get element by ID, which is the one I used previously. And there's other ones, like by class name, by name, tag name, and so on. So if you use by class name, that's the one that it's going to find by the class. But there's a problem here. You notice there's an s here, so it's plural. Why is that? Because multiple elements can have the same class. So that's why it's always going to capture one or more, or nothing at all. So you've got to be aware of that. Now, I can assume here there's only one of them. So I can go with that. So I'm going to call this function with JS, that image separated by a dash, which has to match exactly the class name there. Now, because this returns many things that could return many things, we've got to kind of learn about what are called arrays in JavaScript. So let me just take a step back here and show you what that is. I'm going to the browser, to the console, in the DevTools. So in JavaScript, there are different ways you can store things. And for example, if I want to store a number for calculations, I can say a equals 3 and b equals 4. And then whenever I say a, I get 3. Whenever I say b, I get 4. Why is that? These are called variables. They store information for us for later use. So when I say a equals 3, I'm defining that a is now have the value 3. And b now have the value 4. So whenever I say a, you're going to get 3. Say b is 4. So I can do like a times b. And imagine a is replaced with 3. And b is replaced with 4. And 3 times 4 is 12. So you get that, and press Enter. That's the concept of variables. Now, you might think, OK, what if I have so many numbers, like CD, EFG, a sequence of things? Can I just, I would have to write like, if I had 100 things, like 100 times, that's tedious. Isn't there a way to group them all together into a single thing? That's when arrays or lists come along. So I can say like numbers equal square brackets. And I can say 3, 4, and then 6, 9, and so on and so on. A sequence of numbers that I want to store. Now, the notation is square brackets surrounding the number separated by the comma. And the equals sign is because I wanted to find the variable numbers. So you can see it reads array of 4. And it's like a list of things. And there are many things inside. Those things are called elements. So we have the first element 3, second element 4, third element 6, and the fourth element 9. OK, the browser is nice enough to provide us with this kind of live view preview that I can expand to see what each of them is. And it even has the length property that tells you how many elements there are. Now, you might notice, what are these 0, 1, 2, 3? These are the positions of each of these numbers. And they're called the index, OK? Index. And we always count them from 0. So if you want to find the first element, that's the position or index 0. And if you want to get the second one, it's position index 1. So you always have to subtract 1 from the actual English counterpart. If I want the fourth element, it's 4 minus 1, which is index 3. This one. Now, that's nice. But how can we access them in code, right? If I want to access the first element in the list, I use the name of the variable, square brackets, and you put the index between the square brackets. Like, numbers square brackets 0 gives you the first element. And then square brackets 1 is the second. Square brackets 2 is the third and 3, 4. And if I try 4, it doesn't exist, right? It's undefined. OK, so that's the constable array. Now, let's go back to the getElementsByClassName. Now, I actually can demonstrate that. Let me see if I go here. I actually want to demonstrate that in the code. I'm just going to leave this like this, save it. And I'm going to open my file in a browser externally, because I want to leverage the DevTools to also show you how we can debug that. So I'm going to go back. Let me use Chrome now for people who are using Chrome. It's the same thing. Here in Google Chrome, open DevTools. I'm going to refresh this to get the new code. And if I go here and click this pointer and point to the image, I can see the image here. It has a class, right? So let me play around with that if I go to the console. And let's do document dot get. And you can see there's auto completion, getElementsByClassName, parentheses. We're going to pass JS path image, close that. And you see what you get there. You can press Enter, and it will return something back to you. Now, this is called hdmlCollection, which is kind of like an array. So you can expand this. And you can see 0 is the index. 0 has the first element, which if I highlight that, it's the image itself. And the length is the number of elements. So you can think this as an array. So if I want to access this first element, how would I do that? If I put this in a variable, let's say that's the path images. I would use the same thing I taught you just now, path images brackets 0. And that will give me that first one, which matches this image. Now, why do we have to do that? Because this functions getElementsPlural. So it returns more than one thing, a list of things. You can think that as an array sequence of things. That's why we've got to do this trick of square brackets 0, if we want to actually get that reference to the image. So if I press Enter, you've got the image there. And then once you've got the image, you can manipulate it to change the style, right? We can do dotStyle. By the way, I press the app arrow in the keyboard to go to the last thing I typed. So you can browse through what you typed before. So I'm going to do that dotStyle. And if you press Enter, you can actually investigate what's going on inside that object thing. And you can see it's all the CSS stuff, all the properties. So you can investigate and learn all their names just by doing that. So I want to do the border, right? So there's so many ones for borders. And there's the shorthand, which is what I want to do here. So I'm going to go here, press up again, and dotBorder. And then to change it, I got to use equal sign. And then quotes. Let's do 3px solid and black. How about that? And Enter. And you see now I got a border there surrounding the image. OK, so we're going to just copy this code back into our thing. I can just paste it here. This actually works. OK, let me see. And I have to put the brackets here. Get elements by class name, jspad image, dotStyle, double, OK. When I click, yeah, there you go. Let me refresh. So this thing here returns the list of things, like the HTML collection. And you don't have to put that in a variable first. You can just leave it here. And imagine the list of things would be there, like this. Image, image2, image3, if there is any. And then when you do sub0 out of that, it's going to get the first image. And that's why it works. Now, this is only doing it when I click, right? Because if you remember, I have a click attribute on the image. So when I click the image, it will call this function add border. So we'd go jump here to all these statements from the top to the bottom between the color base. And then we'll execute them. So it will find that list of HTML collection. And then from that list, we extract the first element, which matches this image. And from that image, we go to the style and then finally change the border property to the right-hand side. And then when I click, that happens. OK. Let me know if I have any questions. OK. So let me teach you something interesting. How about we add a button here. Next to the image. So to make a button, OK, is the button element like this. And closing tag between the tags, let's say path to dog. Let me see if we can put an emoji of the dog here with a hand wave like that. So what I want to do is the following. When I click the button, I want this player or sound to play. This is basically, if you recall, there's an audio. If I click play, I hear the dog's barking. So I want to click the button and automatically play that sound for me. And I'm going to leverage the audio element that already exists in a page. And all I have to do is ask that to play with JavaScript. So OK, what's the event? Click the button here. So let's go. We got this button. We need a way to make it identify it through JavaScript. So you can either give ID, a class, or any of those things. Let's add here. Let me just put type button here for the sake of not it being submit for the form. And let's use ID. And I'll teach you yet another way of selecting another function. Let's call that path button. And we're going to go here and add a non-click. So when I click this button, I want to call the function bark and parentheses. Don't forget parentheses. I'm going to go here to the script and write some JavaScript. But before I do that, actually, we usually don't write JavaScript in the same file as HTML, unless we're doing reactivates. So we want to like CSS that we write the styles in a separate file. We can do the same for JavaScript. So let's do that, actually, while we're at it. I'm going to go here and create a new file called news.js. That's the typical extension for JavaScript. Although if you're using TypeScript, you might see TS. If you're doing react, it's JSX or TSX. Anyway, make another file.js. So I'm going to split that down here, right-click, so I can see it at the bottom. And in my news.html at the top, I'm going to go between the tag script. I'm going to cut all the code and paste to news.js and fix all my indentation with shift tab like that. I'm going to save it. Now we need to link the files. And the way you do that is basically you leave the script there and add a source attribute and the file name news.js. And then you don't have to have anything between, but you still need the closing tag. So don't forget to leave it here. Now it still works if I click there if I test it. Again, I changed my code. I refactor it. You want to make sure to test it again to make sure the behavior is the same. So you want to click that and see it behave the same way as before so it's not broken. OK, that's great. Now let's add the bark function here, function. So outside of this, make sure it's outside. When I say outside, it's after the closed hurling brace here or before the function keyword here. So either here or here, line 7. So function bark. And then we need to define the inputs to the function with parentheses. And I'm not going to have any, so empty. And then define the instructions between the curly braces. Now, how can we play the audio? Well, the audio is part of the element audio here. So we need a way to access that. So actually, this ID for the pet button should be there for the audio, not for the pet button. Because the pet button is already captured here. So let me move this ID from the button to the audio, actually, as an attribute. I'm going to call it pet audio. So I can capture this audio by the ID. And then I can ask that to play a JavaScript. So how can I capture? I could do get element by ID. That's one way. But let me show you another one that you might also see. That's pretty much the most popular way. That's through the query selector function. So there's two variations. The first is query selector and the square selector all. Where selector only finds one thing. Where selector all finds multiple things, which is like the get elements by class name. So we got to do the square brackets. So I know there's only one element, pet audio. So I use query selector. And here in the function call argument, I need to pass a CSS like selector. So remember, if you want to select this with CSS, ID means hash, right? Start with hash, pet audio. So you would write the same thing here. But you got to be on the quotes, hash, pet audio. Because it's a string, OK? String has quotes. So this is saying, I want you to find in the document an element that has the ID, pet audio. The hash means ID, right? And from that, you can get the audio. And the audio has a method called play. And I just told you another new word. So another word that you might hear for function is method. And the reason for that is when you have functions that don't belong to any object that are just functions, but when they belong to an object like the case here, it's called a method. So you might hear that. Anyway, we're going to call play with the parentheses like that. When I click the button here, I hear the dog's barking. You can see the player already triggered without me even clicking the player. And yeah, so likewise, you could actually take this button away and make you click the image. And when you click the image, it would bark. So all you have to do is move this thing here like that. Or you could change your function for the image. When you click instead of that bar, you put bark. That way, when I click, it's barking again. So that's something you could change. Be nicer. So that's something you could change. Be nicer. Anyway, I'm going to revert back to add border. Somebody asked, can you find an element by class name or tag using the query selector? Absolutely. Just use the CSS equivalent. So how do you select something by class and CSS? What's the prefix? Dot, right? So I'll use dot. So if I don't have a dot, that's by the tag name. I could do audio here, except if I do that, it works, right? But there's an assumption there's only one audio in the document, so I don't recommend doing that, right? So anyway, is everybody doing any more questions? And now to save that, I want to actually do some git stuff. Since we learned git, I'm actually going to show you how you would do these. So I would do git status here. I see there's some change, right? And I would do git add or git diff first to see what was changed. I can see I had an ID here in my image, kind of has this class and so on, right? You can see what happened there. So you can do the git add source news.html. That goes to the staging area, and you still got to commit that. And then it can also add the source news.js that's not tracked yet. And now both of them are in the staging area, and I would do git commit and write my message press enter. And then I would do git push to my origin, master, because I'm a master branch, but right now. But typically, you would check out a new branch, right? Get checkout dash v, maybe bark on click or something like that. And then you'd commit, and then eventually you make a pull request on GitHub. But since we don't have that here, I'm just doing it by myself, so I would just push this. But anyway, I want to leave that for later, because I might write more code. But there's nothing wrong with adding multiple commits, right? Anyway, OK, so let's see what else we can do here. How about I quickly show you how to build like a kind of image gallery? Let me see. So let's add another button here. Step, pat the dog, put a next image, about next image. So I want to click next image and replace this image with another one, kind of like an image gallery that you see on websites. So I need to, when I click the button, something will happen, right? I need a set of instructions. So let's add on click. And that's called a function next image, and I'll add the parentheses. Go to the JavaScript file, function, next image, parentheses. And then here we got to go and manipulate the image. So we change that to another image. What in the HTML element, what can we change to modify that to another image? What controls what's going to be shown? What's the attribute? It's the SRC attribute, right? This one. So if you change that value inside, you change the image. So we got to manipulate that, OK? So let's capture this image first. So that's JS batch image class. Let's do the query selector. OK, let me repeat it slowly. Document dot query selector parentheses. We're using a CSS like selector. So quotes dot, right? Because it's class JS dash bet dash image. Remember the same thing for the class value here, line 12. And then I can change dot SRC, actually. I can say dot SRC. I can say dot SRC. Remember, usually the dot notation, the thing on the right, belongs to something on the left. And you can think of this whole thing as the image itself. So you can think that as the image here. And it's going to be replaced there. And it can kind of chain with the dots. You can dot on that and change the SRC with the equals sign to something else under quotes. Let me find another URL. Maybe this one of the cat. Let me see. Yeah, I'll paste it to the Zoom chat. OK, so when I click Next Image, the function Next Image will be called. So we're going to go here from the top to the bottom between the curly braces. We're going to find the image. Let's change its source attribute to the right-hand side value, which is a URL I copied from the browser address bar when I was looking for images. And that's changing to that cat image. Now, how can I make it like an actual gallery of multiple images? Well, you would use an array for this. So let's make a list of URLs to images. So I could actually isolate that. Let's do that following. So outside of this function, let's make a variable to hold a list of image URLs. And to make a variable JavaScript, like I told you, you have to have a name. Let's call images and then equals sign as square brackets for the list or array. Now, this variable, we need to only define it once. So we need a keyword const before the name, because that's bar JavaScript syntax. There could be other keywords like let of bar. But usually, you start off with const. If you ever need to replace the value of images, you would change that to let, but that's not the case here. So I'll just start off declaring the variable with a const. And then between the square brackets, you can put the sequence of image URLs. Just like we did for numbers, we can actually use sequence of characters, so-called strings. So the first one would be the Dalmatian, right? So I could copy from my source code here and paste it here. So I just took that here and copy it here under quotes. And I could put comma and put another one, which is the cat here. I'm going to take this one from the cat and paste it there. Now, I notice this is really ugly and long in one line, so we usually break lines for readability. So when I have the open square brackets, I put a line break. When I have the closing before that, it's a line break. And then for each element, after the comma, I break a line, so it's very easy for us to visualize. OK, now we got two. Let's find another one for the sake of example. I have this one of the elephant. So I'm going to put a comma here and then paste that. The quotes don't matter. It can be double quotes. So I'm going to paste that on the Zoom chat. And now we want to go to the next image based on this list. So initially, I have to be here. When I click next, I want to go to the other one. When I click next, I want to go to the other one. And if you want to cycle, you can go back to the beginning if you wish to do so. How do you do that? Well, we need a way to keep track of what image index we're showing right now. Remember, the index we start counting from zero. So let's create another variable. Let's call it image index. Let's call it current image index to be more precise. So we will usually name our variables very descriptive for what they are storing. And let's make that have value zero. And remember, if we put cons, we have to think, will we change this value later? We actually will change that after the first time because we need to increment that to 1 and into 2 every time I click next. So I have to make that let variable. Because let allows you to change the value of the variable later on after the first assignment. OK, so the current image index is zero, which points to this. When you think about the array, remember, we can image sub zero to get the first element, sub one to get the second, and sub two to get the third. So you'd actually reference this variable name here like this. So whenever you need to get the image to show, you would do that. And then you have to increment current image index first before doing the next. OK, let's see how we do. So let's go step by step. When I click next image, it will call this function. So we are going to go here. What do we do is the following. OK, I want the next image. Therefore, the index has to change to whatever it is right now, plus one. So we take current image index, we add one, and we add one, and we add one. Image index, we add one. And then we replace that with whatever was there for image index. Does that make sense? So the new current image index is incremented and gets and replaces whatever was there. So if current image index is zero right now, it would take zero and put it here, execute the right hand side to get one. And then finally, that would be assigned to the left hand side, which is that. So current image index would become one. And then the next time it becomes two and so on. Let me revert that back. So this is what that means. It's just math. OK, then finally in the source, the right hand side has to come from the list, right? Cannot just write the code there. So what's the name of the variable holding that list? It's images. So I can say images here. Now I need to access elements. So square brackets, what's at the index? If I put zero, it's always going to be the first one. If I put one, it's always going to be the second. If I put two, always the third element. How can I vary that? I want to base that based on the value of current image index. So I can actually put that here. And every time it's going to replace, the first time is going to be a one, right? Because it added from zero to one. And the second time is going to be two and so on. So if you click next image, it's the cat, which is this one, right? Current image index is one. If you click next image, it's going to increment current image index. So it's going to take one plus one, which is two, assign that to current image index. It's going to access images at two, which is this one or the elephant, and assign that to the source attribute of the image. So oh, I did too much, sorry. And it's going to be the elephant there. And if I click next, it's going to actually break, right? Because there is no elements after that. It's undefined, right? If you want, you can actually cycle back to the beginning. That's one way. And to do that, use the module operator. No, you don't have to do a loop. If you want to cycle back to the beginning, you can actually use the module operator. Let me show you here in the browser. Let's say I have a list, right? List equals one to, let me say A, B, C. So list sub zero, right, is A, sub one is B, sub two is C. Now, the next one to be undefined, it doesn't exist. How can I make the number go from two back to zero? Actually, let me see. If I take zero percent, how many elements have we got? We got three, right? So percent three, one, two, three, back to zero. Four, five, back to zero. I don't know if you noticed that. So this is the module operator. It takes the remainder of the division. So when it hits three, three divided by three is one remainder. Zero, so it takes zero remainder. So it goes back to zero, which is the index that we want for the first. And then if you have four, it'll be one and so on. So basically, when it reaches three, you can kind of make it go back to zero by just percent the number of elements, which in this case says list.length. That's how you access how many elements in the list. Like you can have a list of any size. If you say .length, it will be whatever that size is. Otherwise, you cannot possibly change the list and then your code would break if you hard-code the number here. OK, let's do that. So here, what you're going to do is take this. You're going to percent with the images.length. Like that. I think that will work. Actually, we don't do this here, sorry. We're doing the computation here. That's better. So whenever you computed the next one, if it happens to be, for example, if this thing is three, right, if you have like two there, plus one is three, percent three. The remainder of the division is zero. So that becomes zero. By the way, the parenthesis here is important because of mathematical precedence. So if you don't have the parenthesis, you're going to get some bug. And I made that mistake before, so let's see. Let's test it out. OK, current image that is now what? A one, right? Now it's two. It's going to go two plus one, three, percent three. That's going to be three divided by three is one, remainder zero. So this is going to be zero. And there you go. And then the next, the next, going back, right? It's always the same index when you percent with the length. And as long as that index is less than that number, the percent operation is always going to give back the same thing. But when you hit the same right hand side, which is three, it will zero, right? Go back to zero. So no need for a loop here. And then with this mechanism, it can actually add a lot more images. And the code will work no matter how many images you've got. Let's say I had a completely new image here. Let's say we find something on the internet. Let's go to Google Bing.com. A bird about that images. Let's try this one, view image copy. Let's hope they let us use the URL. Let me add to the list of images, another one under quotes. And let's see. There you go. And if I go to the next, it goes back to the beginning. So no matter how many images you've got, those work the same way. So it's very scalable. The mechanism will work no matter the number of images you place here. So all you got to do is add another link or URL here. And it will work the same. Now as an exercise, maybe you might want to implement the previous. How about you add previous here, add a button, type button, on click, previous image function, previous image button. So when I click previous, I want to go back to the previous one. So you would make a function here, previous image. And then you're going to do almost the same, right? Except you have to, what, subtract, right? And you got to think about what happens if it goes negative, right? How can I go from the beginning to the end? Remember, the end is what? The index of the end is always the array length minus one. Right? So you, to do exercise. I'll let you figure that out. If you have questions, ask in the discord. But yeah, and with that, I finish the lecture.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: