What's new
HTML Forums | An HTML and CSS Coding Community

Welcome to HTMLForums; home of web development discussion! Please sign in or register your free account to get involved. Once registered you will be able to connect with other members, send and receive private messages, reply to topics and create your very own. Our registration process is hassle-free and takes no time at all!

Where is the error in the code? Is there an error?

flunger96

New member
Hello, i am new to the forum!

I have a question in JS ( am a beginner obv.).

I am programming a website (following a tutorial) and the goal is to to have a display of 5 images, when you click on one it becomes the large main image, and when you click on another, this one will become big.

Help me with the JS code in the image please. The function .onclick is not working for me. In my HTML file are 5 images with the class tag "smallimg". These should be reffered to by the var smallImg. But it is not working like it should in the image. Solution?
 

Attachments

  • jsproblem.jpg
    jsproblem.jpg
    65.5 KB · Views: 3
Last edited:
Flunger96,

Instead of using document.getElementById(), try using querySelector() for individual element selection and quwrySelectorAll() for managing element collections.
Note the difference in selection elements by their ID or Class Names

Here is an easier way to assign click events to a collection of elements ("small-img" elements). This method bypasses the need to identify the element[index) and can be instantiated on window.onload()

JavaScript:
    <div style="display: grid; width: 80%; place-content: center; padding: 2rem"><img src="images/blank.png" alt="" id="productImg" /></div>
    <div><img src="images/image-1.png" alt="" class="small-img" /></div>
    <div><img src="images/image-2.png" alt="" class="small-img" /></div>
    <div><img src="images/image-3.jpg" alt="" class="small-img" /></div>
    <script>
        var ProductImg = document.querySelector("#productImg");
        var SmallImg = document.querySelectorAll(".small-img").forEach(function (smallImage) {
            smallImage.addEventListener("click", (e) => {
                    ProductImg.src = e.currentTarget.src;
            });
        });
    </script

Hope this helps.

aCodeMonkey
 
Back
Top