Add/remove Class To A Button
I'm having problem adding new class to a button. Button arrow should be showing right(fa-angle-right) when sidebar is closed. And left (fa-angle-left) again when it's open. https:/
Solution 1:
Couple of things, the you should use toggleClass for switching classes, it's more concise. Additionally, I'd use the relative selector .find
so that you can support multiple buttons. To only address the question, you did typo sidebarToggle
. After fixing the typo it worked.
(function() {
var $sidebarAndWrapper = $("#sidebar, #wrapper");
$("#sidebarToggle").on("click", function () {
$sidebarAndWrapper.toggleClass("hide-sidebar");
$(this).find("i.fa").toggleClass("fa-angle-left").toggleClass("fa-angle-right");
});
})();
/* minified because I only changed JavaScript */
#main{background-color:#aea9a9;padding:4px;margin:0}#footer{background-color:#808080;color:#eee;padding:8px 5px;position:fixed;bottom:0;width:100%}.headshot{max-width:50px;border:1px solid #808080;padding:3px}.menu{font-size:12px;color:aquamarine}.menu li{list-style-type:none}.menu li.active{font-weight:bold}#sidebar{background:#525050;color:aliceblue;position:fixed;height:100%;width:250px;overflow:hidden;left:0;margin:0;transition:left ease .35s}#sidebar.hide-sidebar{left:-250px;transition:left ease .35s}#wrapper{margin:0 0 0 250px;transition:margin-left ease .35s}#wrapper.hide-sidebar{margin-left:0}
<!-- minified because I only changed JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body> <div id="sidebar"> <span id="username"></span> <ul class="menu"> <li class="active"><a asp-controller="App" asp-action="Index">Home</a></li><li><a asp-controller="App" asp-action="About">About</a></li><li><a asp-controller="App" asp-action="Contact">Contact</a></li></ul> </div><div id="wrapper"> <div id="main"> <div> <button id="sidebarToggle" class="btn btn-primary btn-sm"> <i class="fa fa-angle-left"></i> </button> </div><div> <h2>The world</h2><p>This will be a fun website soon!</p><form> <div> <label>Date</label> <input/> </div><div> <label>Location</label> <input/> </div><div><input type="submit" value="Add"/></div></form> </div></div><div id="footer"> <h5> © 2017 The World Ltd.</h5> </div></div><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <script type="text/javascript" src="~/js/site.js"></script></body>
Solution 2:
Your spelled sidebarToggle
wrong -_-
var $icon = $("#sidebarToggle i.fa");
Post a Comment for "Add/remove Class To A Button"