3D-kreativ
3D-kreativ

Reputation: 9319

Swap images with jQuery

I have several articles on the webpage and each article has a main image and some buttons to load and swap the main image. The problem with my jQuery script below is that it affects all main images inside all articles, I just want to swap the main images within in the article where i click on it's button. Is this possible?

HTML (I have several articles like this on the webpage) :

<article class='post'>
<header><h2>Metropolis</h2></header>
<img src='images/buildings/large/metropolis-1.jpg' alt='Metropolis Köpenhamn' class='postImg mainImage' >
<div class='infoContainer'>
<div class='buttonContainer'>
<ul>
<li><a href='images/buildings/large/metropolis-1.jpg' >1</a></li>
<li><a href='images/buildings/large/metropolis-2.jpg' >2</a></li>
<li><a href='images/buildings/large/metropolis-2.jpg' >3</a></li>
</ul>
</div>
</div>
<div class='plus'><img src='images/icons/arrow-down.png'></div>
</article>

jQuery:

    $(".buttonContainer ul li a").click(function(event) {
    $(".loader").show();
    var btnNum = $(".buttonContainer a").index(this);
    var btnUrl = $(this).attr("href");
    var imgNew = $("<img />").attr("src", btnUrl).load(function() {
        $(".mainImage").attr("src", imgNew.attr("src"));
    $(".loader").hide();
    });
     return false;
});

Upvotes: 0

Views: 66

Answers (1)

Sachin
Sachin

Reputation: 2775

$(".buttonContainer ul li a").click(function(event) {
 var btnUrl = $(this).attr("href");
 $(this).parents(".post").find(".mainImage").attr("src",btnUrl);
});

Updated

Edit(unchecked)

  $(".buttonContainer ul li a").click(function(event) {
 var btnUrl = $(this).attr("href");
  $(".loader").show();
  $(this).load(function{ $(".loader").hide();});
 $(this).parents(".post").find(".mainImage").attr("src",btnUrl);
});

Upvotes: 2

Related Questions