On click function problem

I have been giving an assignment in my college to build a website and one of the pages I am struggling on because I have been asked not to use on-click on HTML and JSON file, the page is a shopping cart and all I want to do is on JavaScript is when I click on the small image I want to change the large image by the small image source.

Are you allowed to use other events?

Good luck with your assignment

Can you show your attempt?

<div class="products-img">
            <div class="prd-display-img">
                <img id="d-img" src="1.jpg" alt="Products Image">
             </div>
            <div class="prd-slide-img">
                <div class="prds-imgs">
                    <img onclick="change_img(this)" src="1.jpg" alt="products Images" class="p-imgs">
                    <img onclick="change_img(this)" src="2.jpg" alt="products Images" class="p-imgs">
                    <img onclick="change_img(this)" src="3.jpg" alt="products Images" class="p-imgs">
                    <img onclick="change_img(this)" src="4.jpg" alt="products Images" class="p-imgs">
                    <img onclick="change_img(this)" src="5.jpg" alt="products Images" class="p-imgs">
                    <img onclick="change_img(this)" src="6.jpg" alt="products Images" class="p-imgs">
                </div>
            </div>
        </div>
 function change_img(image){
    document.querySelector('#d-img').src = image.src;
}

--------my html and java-------
as you can see i use " onclick=“change_img(this)” " and it works but I can not come up with any other opation to use java only

You should read about the addEventListener method that can be attached to DOM elements. You could listen for click events on the div with class="prds-imgs" and if target of the click event is an img element, change the image.

i am new to java so could you give me a sample code? thanks

You can read about the method with a few examples here on MDN.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.