javascript - How to jQuery toggle conditionally and add classname? -
i'd have button, when clicked add classname "in" or if "in" exists remove it.
it add "in" class once set doesn't remove when clicked again.
how can add "in" class "collapse" , remove when clicked again?
$(document.getelementbyid("toggle-expand-sections")).click(function() { if ($('#toggle-expand-sections').hasclass("enabled")) { $('#description-form .collapse').addclass("in"); } else { $('#description-form .collapse').removeclass("in"); $('#toggle-expand-sections').addclass("enabled"); } $('#toggle-expand-sections .toggle').toggle(); });
#toggle-expand-sections { text-align: center; margin: 0 auto; padding: 2rem; } .collapse { display: none; } .in { display: block !important; }
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/js/font-awesome.min.js" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="toggle-expand-sections" class="btn btn-info"> <i class="fa fa-toggle-off toggle" title="expand sections"></i> <i class="fa fa-toggle-on toggle" style="display: none" title="collapse sections"></i> </button> <div class="collapse"> <div class="subheader-description">foo</div> </div> <div class="collapse"> <div class="subheader-description">bar</div> </div> <div class="collapse"> <div class="subheader-description">baz</div> </div>
you didn't know .toggle()
method...
description: display or hide matched elements.
see how reduces code (and chances of error, logical or syntaxic).
// toggle "expand/collapse sections" button $('#toggle-expand-sections').on('click', function() { $(this).find('.toggle').toggle(); $(".collapse").toggle(); }); /* if ($('#toggle-expand-sections').hasclass("enabled")) { $('#toggle-expand-sections').removeclass("enabled"); $('.collapse').removeclass("in"); } else { $('.collapse').addclass("in"); $('#toggle-expand-sections').addclass("enabled"); } }); */
#toggle-expand-sections { text-align: center; margin: 0 auto; padding: 2rem; } .collapse { display: none; } /* .in { display: block !important; } */
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/js/font-awesome.min.js" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="toggle-expand-sections" class="btn btn-info"> <i class="fa fa-toggle-off toggle" title="expand sections"></i> <i class="fa fa-toggle-on toggle" style="display: none" title="collapse sections"></i> </button> <div class="collapse"> <div class="subheader-description">foo</div> </div> <div class="collapse"> <div class="subheader-description">bar</div> </div> <div class="collapse"> <div class="subheader-description">baz</div> </div>
Comments
Post a Comment