Reputation: 131
(First code)
$(document).ready(function () {
var $answers = $('.result_menu');
$(".result_location").click(function () {
var $ans = $(this).next(".result_menu").stop(true).slideToggle(300);
$answers.not($ans).filter(':visible').stop(true).slideUp();
})
(Second code)
.toggle( function() {
$(this).children("img").attr("src","./img/icon_1_expand.png");
}, function() {
$(this).children("img").attr("src","./img/icon_1_collapse.png");
});
I have toggle options and the first set of code works fine, and it toggles the second set of code, but I have four divs, that I need the second code to toggle “arrows” to basically on close or slideDown on other divs when it is clicked to slideUp.
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
I have four divs, and when “1” is clicked, it slides up with info, and then when another is clicked the current one closes and new one opens. All that works fine, but I have arrows on each that when clicked the arrow toggles to different image. All that works fine, except when one is open and another is click the toggle image arrow doesn’t change on the that just closed when other was clicked.
Upvotes: 1
Views: 470
Reputation: 1806
Basically this is the traditional Accordion (or collapse)
components in some famous UI frameworks.
The promblem here is that you use the jQuery.toggle()
function in the wrong way. .toggle()
means "hide or show" a set of elements in jQuery. You are not able to pass two handlers to the .toggle()
function. The official document is here.
In your case, if all you want to do is change the display images in different states, you can simply use .toggleClass
. So when the heading is clicked, you can remove the active class for the first image and add the active class for the other one. Then you can use background image to change for different states. It may be something like this:
// js file
$(this).children(".img").toggleClass('active');
// css file
.img {
background-image: url(./img/icon_1_expand.png);
}
.img.active {
background-image: url(./img/icon_1_collapse.png);
}
You may see the Codepen example here.
Upvotes: 1