Loading
Lesson 35
Courses / Software School Cuts
Clicking Next Calls JavaScript Function to Change the Image

Learn how to listen to click events in JavaScript to execute a set of instructions.

In particular, you learn to click a button to change an image to another one. This feature is a very basic one from image galleries where you click a next button and the current image is replaced with the next one.

Summary

Gallery Creation Tutorial Summary

This tutorial outlines the steps to create a simple image gallery using HTML and JavaScript. Below are the key points discussed:

Steps to Create a Gallery

  1. Setup the Initial HTML Structure:

    • Start with a clean slate by deleting existing content.
    • Add an image by specifying the source and alternate text.
    • Set width and allow height to adjust automatically.
    <img src="image_url.jpg" alt="A dog" width="100">
    
  2. Add a Button:

    • Create a button to trigger image changes when clicked.
    <button type="button" onclick="changeImage()">Next Image</button>
    
  3. Setting Up the JavaScript Function:

    • Define a JavaScript function changeImage() that changes the image source when the button is clicked.
    function changeImage() {
        const img = document.querySelector('img'); // Select the image
        img.src = 'new_image_url.jpg'; // Change the source to a new image URL
    }
    
  4. Element Selection:

    • Use document.querySelector('img') to select the first image element in the document.
    • Optionally, you can also select elements by class or ID.
  5. Debugging with DevTools:

    • Utilize browser DevTools to inspect elements and test JavaScript commands.
  6. Image Source Manipulation:

    • Change the image's src attribute directly by assigning a new URL.

Example Code Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Gallery</title>
</head>
<body>
    <img id="gallery-image" src="dog_image_url.jpg" alt="A dog" width="100">
    <div>
        <button type="button" onclick="changeImage()">Next Image</button>
    </div>
    <script>
        function changeImage() {
            const img = document.querySelector('#gallery-image');
            img.src = 'cat_image_url.jpg'; // Change this to your cat image URL
        }
    </script>
</body>
</html>

Conclusion

  • This creates a basic image gallery functionality where clicking the button changes the displayed image.
  • The tutorial emphasizes understanding how to work with DOM elements and their properties in JavaScript.

Video Transcript

Now let's talk about making a gallery. Let's delete everything here. Everything here. I need an image. So, okay, I got one image here. So I'm going to add an image source here. Alt, you know, that image. Now it's too big, so I want to give maybe width 100 height. Let it be change automatically. Now that's a little bit bigger. There you go. I have a picture of a dog. So I posted it in the Zoom chat the link I used, but you can find anywhere. Go on your search engine, find a picture, copy the URL from the address bar after you view the picture. Anyway, so I want to add a button here. Element button type button. And I want to see next image. And let me add a div so it goes to a new line, even though it's there because it's too, you know, I want to make it in a new line. So just put a div there. Like that. Now let me remove the CSS. I don't need that. There you go. Now we have an image of a button. So we need to implement when I click the button, I want to change this image. Okay, I want to change it to this other image I'll show you right now. I paste in the Zoom chat. How can we do that? Well, we learned how to listen to click events right before what we do. Okay, we need to find the element we want to listen for the click. Let's just get the button. I can add on click attribute. And I can say here the name of the function we want to call execute when we click the button. Okay, let me say change image. And then we need open and close parentheses. Don't forget because we're calling the function. Now we need to define the function in JavaScript, the function keyword space, name of the function change image, parentheses, curly braces and type the instructions between the open and closing curly base. I like to add indentation, which is the two spaces to the left just for style, you don't have to. But it looks nice. So I can see that all these statements are enclosed within this function body. When I say function body, I mean the things between the open and closing curly brace. Now nice, how can we change this image to something else? Well, the attribute that controls the image is source, right? If we change source to something else here, like I say I go here and copy and paste, that changes it, right? But how can we do that in JavaScript? Well, first we have to select this image. Now I taught you how to target or find this element by ID. Somebody asked for query selector. Query selector is another way of finding an element. So let me tell you how to do query selector. I'm going to say document. Now I can say dot. Okay, what do you want out of the document? Well, I can say get element by ID. That's one way. Or I can do query selector. Query selector is a very convenient way of getting things. I wasn't going to talk about it, but since you asked about it, I'm talking. So it's always the same way. Call it with parentheses, and it needs the argument. It needs to know, okay, what do you want to select? But in this case, let's make it simple. I only have one image in this page. In the real world, there would be many images. So we wouldn't really do that what I'm doing right now. But I'm just going to select by the name of the element. Okay. And if you click runoff, it's going to happen, because this is grabbing that element here. Now query selector is only used to grab one thing. There's another one called query selector, all that grabs many things and kind of returns an array like thing. You know, array, right? We just learned multiple things in one thing. So query selector for one thing. Now, once we got that, okay, I got the source, right? So I think we could just say, actually, let me let me teach you how you can figure it out. I'm going to do the following. I'm going to say console. Actually, can I teach you DevTools debugging? That might be hard. Let me do console, log this and show you something. Let me see if I have the console here. One moment. It's kind of hard to see. Let me see if that's way too many things. Okay. Let me try. Let's see if it works. No, it doesn't work. There, only here. It's hard for me to do the thing I wanted to do because it's within this environment here. And anyway, I just wanted to show you that this is pointing to the element and a way to find out what attribute I would change. Let me search for an image of a dog here. So we have this dog, right? Let me open new image in the new tab. What I'm going to do is open the DevTools. I can inspect this. I can right click. And let me see if they have something into the variable. Yeah, let's do the query selector, document.query selector image. So you can see when I say document.query selector by the element name, it returns the image here. So this image, we can go here. I press the up arrow in my keyboard and I can see dot. And there are many things that suggests out of this value that was returned. And I can look up with things that are of interest. So I can confirm if I scroll all the way up, these are all the properties and operations or functions we can do on this element. And I can confirm that. Where is that? src to csrc. That's indeed here. So I can click that and write that down. And I can assign a new value. Obviously, I put aavc there, which doesn't mean anything. But let me put that other value that I pasted. There you go. Now that's a valid URL. So let me try to summarize here because I might have gone too fast. We use document.query selector. We can query by the element name. As you can see, img. And it will find the first img element on the document. And to that, we saw that we can find out what properties this thing has. And one of them is src, which is the same thing as the attribute for the element that we wrote in HTML. So if I want to change that, I can just do equal sign. Right hand side is the new value. In this case, I changed the image source to be that of the cat. So this is precisely what we're going to do in our code. Does anybody have any questions so far? What was that okay, Javier? Do the query selector. You asked about it. All right. Okay, so I'm going to go back. To our code. And I don't need this console log anymore because I showed you with the dev tools. So we're going to say, I want to change the source. Remember what we're doing here, we want to click next image, the button. So we want to change this image to the image of the cat. So I can see dot source. In this case, it's going to be that URL of the cat, but I have to have what? Quotes. The rounded either single or double doesn't matter in this case. And I always add semi colonize this outer habit, but you don't need to. And when I click next image changes to the cat. Right. Remember, you could be Facebook, Instagram, whatever or a news website. You often see these galleries, right? You click and now the images appears and click another image appears. It's this same mechanism where just manipulating the source attribute of the image and change that to a new value. So the button has a on click attribute that when we click, it calls the function change image that we wrote in JavaScript. So it goes here. Okay, starts on the top. Okay, get element. Not by diva. I'm using query selector. We're going to find, okay, go through all the whole document. The first element that's image, I want that to be returned. I got a reference to that. Okay, I'm going to change the source attribute to the new URL. Have your asks dot class is a class, correct? That depends on the context. If it's writing CSS, when you start dot, that's a class. And also the query selector, you can actually write the same selector for CSS here. So if image, you had a class, say, the image, you could actually do in the query selector dot, meaning find the element that has the class called the image. That's the same thing. If I click run, you know, and I click, works the same way to select the element, right? An element can be found through many different means. You can find it by the its name, you can find it by a class that it has or an ID, or maybe an attribute and so on.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: