Reputation: 2525
I currently have a div
with a default minus sign and when I click on it it changes to plus sign but when I click on plus sign again it doesn't toggle back to minus sign. How can I alter my javascript so that it switches between the classes based on the click?
$(document).on('click', '.header', function (event) {
$(this).nextUntil(".header").toggle();
document.getElementById("toggleIcon").className = "icon-plus";
});
Default is icon-minus and when I click on it it changes to icon-plus and when I click on it again it should switch back to icon-minus but it is not doing that.
HTML
<div class="accordion-group" data-bind="foreach: Types">
<div class="text_x-large header">
<span data-bind="text:Name()"></span>
<span id="toggleIcon" class="icon-minus"></span>
</div>
<div data-bind="foreach: Users">
<!-- ko if: Letter -->
<div class="text_x-large letterHeader list_accordion_toggle" data-bind="visible: $parent.ShowLetter(), text: Letter"></div>
<!-- /ko -->
<div class="type_list_item smoke_hover" data-bind="template: { name: 'list'}"></div>
</div>
</div>
Upvotes: 2
Views: 194
Reputation: 337743
Use toggleClass
to switch the classnames as required:
$(document).on('click', '.header', function (event) {
$(this).nextUntil(".header").toggle();
$("#toggleIcon").toggleClass("icon-plus icon-minus");
});
i have multiple divs when i click on the second or third div it only changes the icon for the first div
In that case you should not be using an id
to select it. Change the toggleIcon
to a class
, and use that.
$(".toggleIcon", $(this)).toggleClass("icon-plus icon-minus");
Upvotes: 6
Reputation: 930
This way it should work:
$(document).on('click', '.header', function (event) {
$(this).nextUntil(".header").toggle();
if($(this).nextUntil(".header").is(':visible'))
document.getElementById("toggleIcon").className = "icon-minus";
else
document.getElementById("toggleIcon").className = "icon-plus";
});
You've forgotten to set icon minus when the div is opened
Upvotes: 1
Reputation: 5013
I would use the following line:
$("#toggleIcon").toggleClass("icon-minus");
.toggleClass() will add the class if it is not present, and remove it, if it is. You can read the full documentation here: http://api.jquery.com/toggleClass/
Your default style for that icon should be plus, and once icon-minus is added, the image should change. That way you don't need to use more lines of code to add/remove a second class.
Upvotes: 0