jqueryjquery-hover

jquery click only loads first image regardless of image clicked


I am trying to display an image in a div based on the thumbnail that is clicked. I have two sizes, small and large, and want to display the large version in the div. I have tried a couple of code amendments based on other answers, but I am no further forward (these are commented out in my code) .

I have produced a JSfiddle to show the problem.

Can anyone help me find the solution?

HTML & JS:

    <div class="banner_slide clearfix">
    <ul>
    <li class="link"><img class="img-swap thumb-img" src="https://www.ryokuyou.co.jp/wp2/wp-content/uploads/2019/06/m01_hyoushi_small.jpg" /><div class="tridown"></div></li>
    <li class="link"><img class="img-swap thumb-img" src="https://www.ryokuyou.co.jp/wp2/wp-content/uploads/2019/06/m01_honbun_small.jpg" /><div class="tridown"></div></li>
    <li class="link"><img class="img-swap thumb-img" src="https://www.ryokuyou.co.jp/wp2/wp-content/uploads/2019/06/m01_tojikata_small.jpg" /><div class="tridown"></div></li>
    <li class="link"><img class="img-swap thumb-img" src="https://www.ryokuyou.co.jp/wp2/wp-content/uploads/2019/06/m01_sabisu_small.jpg" /><div class="tridown"></div></li>
    </ul>
    <img id="banner-img" src="https://www.ryokuyou.co.jp/wp2/wp-content/uploads/2019/06/m01_sabisu_large.jpg" />
    </div>

    $(".img-swap").click(function () {
    var source = $(this).attr("src");
    $("#banner-img").fadeOut(function () {
    //$(this).attr("src", source); 
    $(this).attr("src", $(".img-swap").attr("src").replace("small", "large"));
    //$("#banner-img").attr("src", $(this).attr("src").replace("small", "large"));
    $(this).fadeIn();
    });
    });    

Solution

  • Because once you trigger this line:

    $(this).attr("src", $(".img-swap").attr("src").replace("small", "large"));
    

    The .img-swap class is not unique on the dom, so it picks the frist dom element that matches the class. To fix this, a possible solution is to save in a varible the element that you click on:

    $(".img-swap").click(function () {
        var source = $(this).attr("src");
        $("#banner-img").fadeOut(function () {
          $(this).attr("src", source.replace("small", "large"));
          $(this).fadeIn();
        });
      });