I want to change the image I clicked.

Asked 2 years ago, Updated 2 years ago, 379 views

I would like to change the image I clicked using callback function and animation.
With the code below, when I click on the image in the list, the animation is applied, but the image shows the initial value of sample1 and cannot be changed.
How can I change the image to the one I clicked?

<body>
        <main>
            <h1>Click the image you want to view</h1>
            <img id="image" src="sample1.jpg" alt="sample1">
            <divid="display">
                <ulid="image_list">
                    <li><a href="sample1.jpg"><img src="sample1.jpg" alt="sample1">/a><li>;;
                    <li><a href="sample2.jpg"><img src="sample2.jpg" alt="sample2">/a><li>;;
                    <li><a href="sample3.jpg"><img src="sample3.jpg" alt="sample3">/a><li>;
                </ul>
            </div>
            <script src="jquery-3.6.0.min.js">/script>
            <script src="changeImg.js"></script>
        </main>
    </body>
"use strict"
$(document).ready()=>{
    $("#image_lista").click(evt=>{
        let newImage=$("#image_lista").attr("src");
        evt.preventDefault();
        $("#image").animate({opacity:0, "margin-left": "-100"}, 1000,
        ( ) = > {
            $("#image").attr("src", newImage).animate({
            opacity: 1, "margin-left": "+=100"}, 1000
            );
        });
    }) 
});

javascript html jquery

2022-09-30 22:05

1 Answers

let newImage=$("#image_lista") .attr("src");

newImage is empty because a> does not have the src attribute. You must either change the attribute to the <a> attribute or change it to the <img> child .

Also, ignore the <a> clicked when you write $("#image_lista").attr() to get the attribute from the first element that matches.


2022-09-30 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.