Skip to content Skip to sidebar Skip to footer

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:8px5px;position:fixed;bottom:0;width:100%}.headshot{max-width:50px;border:1px solid #808080;padding:3px}.menu{font-size:12px;color:aquamarine}.menuli{list-style-type:none}.menuli.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:000250px;transition:margin-left ease .35s}#wrapper.hide-sidebar{margin-left:0}
<!-- minified because I only changed JavaScript --><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body><divid="sidebar"><spanid="username"></span><ulclass="menu"><liclass="active"><aasp-controller="App"asp-action="Index">Home</a></li><li><aasp-controller="App"asp-action="About">About</a></li><li><aasp-controller="App"asp-action="Contact">Contact</a></li></ul></div><divid="wrapper"><divid="main"><div><buttonid="sidebarToggle"class="btn btn-primary btn-sm"><iclass="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><inputtype="submit"value="Add"/></div></form></div></div><divid="footer"><h5>&copy; 2017 The World Ltd.</h5></div></div><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"><scripttype="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"