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>
You are using the setter method to check your `src’
instead use
Or even better just check if the source contains the image using indexOf()
EDIT:
You can probably do it like this to prevent all from changing – this is the context the to look for the image
so
would be the same as