Reputation: 808
I'm trying to get slideToggle to swap images based on if a div is expanded or collapsed. I have it working one way, where it will change an image from plus to minus, but it only works on one div and I have multiple and it only works once. It doesn't toggle.
Here is the jQuery:
$(".content").toggle(1);
$(".expand").click(function () {
$(this).next(".content").slideToggle(400);
if ($(".image1").attr('src', "../nathan/plus.png")) {
$(".image1").attr(
'src',
$(".image1").attr('src').replace('plus', 'minus')
);
} else {
$(".image1").attr(
'src',
$(".image1").attr('src').replace('minus', 'plus')
);
}
});
});
The IndexOf() works, but if I was to duplicate the divs they all change when one is clicked. Here is the HTML:
<div class="list">
<h2 class="expand">Title1<img class="image1" src="../nathan/plus.png"></h2>
<div class="content">
</div>
</div>
<div class="list">
<h2 class="expand">Title2<img class="image1" src="../nathan/plus.png"></h2>
<div class="content">
</div>
</div>
Upvotes: 3
Views: 2856
Reputation: 33661
You are using the setter method to check your `src'
if ($(".image1").attr('src', "../nathan/plus.png"))
instead use
if ($(".image1").attr('src') == "../nathan/plus.png"))
Or even better just check if the source contains the image using indexOf()
if ($(".image1").attr('src').indexOf("plus.png") > -1)
EDIT:
You can probably do it like this to prevent all from changing - this is the context the to look for the image
$(".expand").click(function() {
$(this).next(".content").slideToggle(400);
var $img = $(".image1", this);
if ($img.attr('src').indexOf("plus.png") > -1) {
$img.attr('src', $img.attr('src').replace('plus', 'minus'));
} else {
$img.attr('src', $img.attr('src').replace('minus', 'plus'));
}
});
so
$(".image1", this);
would be the same as
$(this).find('.image1');
Upvotes: 2